I don't exactly remember what this code did, but it was part of my internship work. I guess you are smart enough to figure it out
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { Route, Redirect, withRouter } from 'react-router-dom';
import AppShell from '../../components/Appshell';
import Loader from '../../components/Loader';
const LoaderScene = ({ location }) => (
<AppShell location={location}>
<Loader />
</AppShell>
);
LoaderScene.propTypes = {
location: PropTypes.shape({
pathname: PropTypes.string.isRequired,
}).isRequired,
};
class ProtectedRoute extends Component {
componentDidMount() {
const { token, dispatchVerifyToken } = this.props;
dispatchVerifyToken(token);
}
render() {
const {
component: RenderComponent,
render,
token,
loading,
location,
...rest
} = this.props;
if (!process.env.BROWSER) {
return <LoaderScene location={location} />;
}
if (loading) {
return <LoaderScene location={location} />;
}
if (typeof token === 'undefined') {
return (
<Redirect
to={{
pathname: '/login',
state: { from: location },
}}
/>
);
}
if (RenderComponent) {
return <Route {...rest} component={RenderComponent} />;
}
return <Route {...rest} render={render} />;
}
}
ProtectedRoute.propTypes = {
component: PropTypes.func,
render: PropTypes.func,
token: PropTypes.string,
location: PropTypes.shape({
pathname: PropTypes.string.isRequired,
}).isRequired,
dispatchVerifyToken: PropTypes.func.isRequired,
loading: PropTypes.bool.isRequired,
};
ProtectedRoute.defaultProps = {
component: undefined,
render: undefined,
token: undefined,
};
export default withRouter(ProtectedRoute);
Aakash Mallik
S/W Engineer @ Samsung R&D Delhi
As far as my implementation goes, we too stored a token in the local storage and check against this value to find out if the user was logged in or not, on top of that, we modified the Route component and created a ProtectedRoute that would implement this logic of checking whether a given route is a valid one as per the token value, if it were not, we would render the Redirect component as mentioned in the react-router-dom docs. I don't think there is anything smart to be done here... Ask me more if I haven't made myself clear.