This is for authentication, when users access certain pages by typing in the URL on browser, they will get redirected to the login page because they haven't login yet.
Let's assume after login successfully, you save the token in local storage
localStorage.setItem('access.token', token);
Now, let's write the HOC called withAuthentication
import React, { ComponentType, FC } from 'react';
import { Redirect } from 'react-router-dom';
const withAuthentication = <P extends any>(
Component: ComponentType<P>,
): FC<P> => (props) => {
const isAuthenticated = localStorage.getItem('access.token) as string;
if (isAuthenticated) {
return <Component {...props} />;
}
return (
<Redirect
to={{
pathname: '/login',
}}
/>
);
};
export default withAuthentication;
What I do in this HOC is very simple. First, I get the token from the localStorage. Then add some conditional to render a component or the Redirect component from the react-router-dom to redirect the user back to the login page.
The HOC in action
import React from 'react';
import {
BrowserRouter as Router,
Switch,
Route,
Redirect,
} from 'react-router-dom';
import withAuthentication from 'hocs/withAuthentication';
function App() {
return (
<Router>
<StyledDivApp>
<Switch>
<Route
exact
path="/dashboard"
component={withAuthentication(Dashboard)}
/>
</Switch>
</StyledDivApp>
</Router>
);
}
export default App;
Comments (0)