Home >Web Front-end >JS Tutorial >How to Correctly Implement Protected Routes in React Router Dom?
Problem
The following code is an attempt to create a protected route in a React application using react-router-dom:
import { useContext } from "react"; import { globalC } from "./context"; import { Route, Switch, BrowserRouter } from "react-router-dom"; import About from "./About"; import Dashboard from "./Dashboard"; import Login from "./Login"; import PageNotFound from "./PageNotFound"; function Routes() { const { authLogin } = useContext(globalC); console.log("authLogin", authLogin); return ( <BrowserRouter> <Switch> {authLogin ? ( <> <Route path="/dashboard" component={Dashboard} exact /> <Route exact path="/About" component={About} /> </> ) : ( <Route path="/" component={Login} exact /> )} <Route component={PageNotFound} /> </Switch> </BrowserRouter> ); } export default Routes;
However, this code does not work as expected. The user is able to access the protected routes even if they are not logged in.
Solution
There are two main issues with the code:
Here is a corrected version of the code that fixes both of these issues:
import { useContext } from "react"; import { globalC } from "./context"; import { Route, Switch, BrowserRouter, Redirect } from "react-router-dom"; import About from "./About"; import Dashboard from "./Dashboard"; import Login from "./Login"; import PageNotFound from "./PageNotFound"; function Routes() { const { authLogin } = useContext(globalC); console.log("authLogin", authLogin); return ( <BrowserRouter> <Switch> <Route path="/" exact> {authLogin ? <Redirect to="/dashboard" /> : <Login />} </Route> <Route path="/dashboard"> {authLogin ? <Dashboard /> : <Redirect to="/" />} </Route> <Route exact path="/About" component={About} /> <Route component={PageNotFound} /> </Switch> </BrowserRouter> ); } export default Routes;
In this corrected code:
The above is the detailed content of How to Correctly Implement Protected Routes in React Router Dom?. For more information, please follow other related articles on the PHP Chinese website!