What are the best practices for authorization checking prior to a component mounting?
I use react-router 1.x
Here are my routes
React.render(( <Router history={History.createHistory()}> <Route path="/" component={Dashboard}></Route> <Route path="/login" component={LoginForm}></Route> </Router> ), document.body);
Here is my Dashboard component:
var Dashboard = React.createClass({ componentWillMount: function () { // I want to check authorization here // If the user is not authorized they should be redirected to the login page. // What is the right way to perform this check? }, render: function () { return ( <h1>Welcome</h1> ); } });
To protect routes, the private components must also have access to the isLoggedIn value. You can do this by creating a new component that accepts the isLoggedIn state as a prop and the private component as a child. For instance, if your new component is named "Protected", you would render a private component like this.
import { Navigate, Outlet } from "react-router-dom"; import { useAuth } from "../hooks/useAuth"; export const HomeLayout = () => { const { user } = useAuth(); if (user) { return <Navigate to="/dashboard/profile" />; } return ( <div> <nav> <Link to="/">Home</Link> <Link to="/login">Login</Link> </nav> <Outlet /> </div> ...
To restrict access to routes in React Router, we set the render prop to a function that renders the component we want according to the condition we're checking. import { Route, Redirect } from "react-router"; <Route exact path="/" render={() => (loggedIn ?
Updated solution for React router v4
<Route path="/some-path" render={() => !isAuthenticated ? <Login/> : <Redirect to="/some-path" /> }/>
React router up to v3
Use 'onEnter' event and in callback check if the user is authorized:
<Route path="/" component={App} onEnter={someAuthCheck}> const someAuthCheck = (nextState, transition) => { ... }
With react-router 4 you have access to the Route props inside the component. To redirect a user you just have to push the new URL to the history. In your example, the code would be:
var Dashboard = React.createClass({ componentWillMount: function () { const history = this.props.history; // you'll have this available // You have your user information, probably from the state // We let the user in only if the role is 'admin' if (user.role !== 'admin') { history.push('/'); // redirects the user to '/' } }, render: function () { return ( <h1>Welcome</h1> ); } });
At the docs, they show another way to do it, by using the render
property, instead of component
. They define a PrivateRoute
, that makes the code very explicit when you define all your routes.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With