Creating a component to protect a route

To protect a route, let's create a new component that will check whether a user is logged in or not. In the first case, the route will be shown, with no further ado. However, in the second case, instead of the original route's component, <Redirect> will be produced, redirecting the user to the login page:

// Source file: src/routingApp/authRoute.component.js

/* @flow */

import React from "react";
import { Route, Redirect } from "react-router-dom";
import PropTypes from "prop-types";

export class Auth extends React.Component<{
loginRoute: string,
token: string,
location: object
}> {
static propTypes = {
loginRoute: PropTypes.string.isRequired,
token: PropTypes.string.isRequired,
location: PropTypes.object
};

render() {
const myProps = { ...this.props };
if (!myProps.token) {
delete myProps.component;
myProps.render = () => (
<Redirect
to={{
pathname: this.props.loginRoute,
state: { from: this.props.location }
}}
/>
);
}
return <Route {...myProps} />;
}
}

We will connect this component to the store so that it can access the current token plus the path to the login page:

// Source file: src/routingApp/authRoute.connected.js

/* @flow */

import { connect } from "react-redux";

import { Auth } from "./authRoute.component";
export const AuthRoute = connect(state => ({
token: state.token,
loginRoute: "/login"
}))(Auth);

Now, we have everything we need; let's make it work!

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.252.201