Creating Protected routes in ReactJS
Protected routes are very important for any web application.
Below are the code to create authenticated routes that only certain users can access based on their authentication roles.
Below are the code to create authenticated routes that only certain users can access based on their authentication roles.
import React, { Component } from 'react';
import { BrowserRouter as Router, Route, Switch, Redirect } from 'react-router-dom';
import commonService from './core/services/commonService';
import './App.css';
import Loader from './views/Loader/Loader';
// Containers
const FrontEndLayout = React.lazy(() => import('./containers/FrontEndLayout/FrontEndLayout'));
const UserLayout = React.lazy(() => import('./containers/UserLayout/UserLayout'));
const loading = () => <Loader />;
class App extends Component {
render(){
return (
<Router>
<React.Suspense fallback={loading()}>
<Switch>
<ProtectedRoute path="/user" name="User" component={UserLayout} />
<Route path="/" name="Home" component={FrontEndLayout} />
</Switch>
</React.Suspense>
</Router>
);
}
}
const ProtectedRoute = ({ component, ...rest }) => {
return (
<Route {...rest} render={routeProps => {
return commonService.getAuth() && localStorage.getItem("role") !== "" ? (
renderMergedProps(component, routeProps, rest)
) : (
<Redirect to={{
pathname: '/login',
state: { from: routeProps.location }
}}/>
);
}}/>
);
};
const renderMergedProps = (component, ...rest) => {
const finalProps = Object.assign({}, ...rest);
return (
React.createElement(component, finalProps)
);
}
export default App;
Thanks for sharing this wonderful content.its very useful to us.I gained many unknown information, the way you have clearly explained is really fantastic.
ReplyDeletekeep posting such useful information.
Full Stack Training in Chennai | Certification | Online Training Course
Full Stack Training in Bangalore | Certification | Online Training Course
Full Stack Training in Hyderabad | Certification | Online Training Course
Full Stack Developer Training in Chennai | Mean Stack Developer Training in Chennai
Full Stack Training
Full Stack Online Training
Great Post. Thanks for posting.
ReplyDeleteReactjs course in Pune
great post on protected routes in reactjs, if you want to get perfection in reactjs then checkout this reactjs classes in pune
ReplyDelete