Home >Web Front-end >JS Tutorial >How to Implement Protected Routes in React Router DOM v5 and v6?
This code, which utilizes React Router DOM and stores responses in localStorage, should create a protected route that allows users to continue viewing their details upon returning to the page. After logging in, they should be redirected to the dashboard page, but the implementation fails to achieve this.
Route Page
import React, { 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;
Context Page
import React, { Component, createContext } from "react"; import axios from "axios"; export const globalC = createContext(); export class Gprov extends Component { state = { authLogin: null, authLoginerror: null, }; componentDidMount() { var localData = JSON.parse(localStorage.getItem("loginDetail")); if (localData) { this.setState({ authLogin: localData, }); } } loginData = async () => { let payload = { token: "ctz43XoULrgv_0p1pvq7tA", data: { name: "nameFirst", email: "internetEmail", phone: "phoneHome", _repeat: 300, }, }; await axios .post(`https://app.fakejson.com/q`, payload) .then((res) => { if (res.status === 200) { this.setState({ authLogin: res.data, }); localStorage.setItem("loginDetail", JSON.stringify(res.data)); } }) .catch((err) => this.setState({ authLoginerror: err, }) ); }; render() { // console.log(localStorage.getItem("loginDetail")); } }
1. React Router DOM v6
In version 6, use an auth layout component instead of custom route components:
import { Navigate, Outlet } from 'react-router-dom'; const PrivateRoutes = () => { const { authLogin } = useContext(globalC); if (authLogin === undefined) { return null; // or loading indicator/spinner/etc } return authLogin ? <Outlet /> : <Navigate to='/login' replace state={{ from: location }} />; }
Update your routes:
<BrowserRouter> <Routes> <Route path='/' element={<PrivateRoutes />} > <Route path='dashboard' element={<Dashboard />} /> <Route path='about' element={<About />} /> </Route> <Route path='/login' element={<Login />} /> <Route path='*' element={<PageNotFound />} /> </Routes> </BrowserRouter>
2. React Router DOM v5
In version 5, create a PrivateRoute component:
const PrivateRoute = (props) => { const { authLogin } = useContext(globalC); if (authLogin === undefined) { return null; // or loading indicator/spinner/etc } return authLogin ? ( <Route {...props} /> ) : ( <Redirect to={{ pathname: '/login', state: { from: location } }} /> ); };
Update your Login component:
export default function Login() { const { authLogin, loginData } = useContext(globalC); const location = useLocation(); const history = useHistory(); useEffect(() => { if (authLogin) { const { from } = location.state || { from: { pathname: '/' } }; history.replace(from); } }, [authLogin, history, location]); return ( ... ); }
Update your routes:
function Routes() { return ( <BrowserRouter> <Switch> <PrivateRoute path='/dashboard' component={Dashboard} /> <PrivateRoute path='/About' component={About} /> <Route path='/login' component={Login} /> <Route component={PageNotFound} /> </Switch> </BrowserRouter> ); }
The above is the detailed content of How to Implement Protected Routes in React Router DOM v5 and v6?. For more information, please follow other related articles on the PHP Chinese website!