Home > Web Front-end > JS Tutorial > How to Implement Protected Routes in React Router DOM v5 and v6?

How to Implement Protected Routes in React Router DOM v5 and v6?

Patricia Arquette
Release: 2024-12-21 22:31:07
Original
412 people have browsed it

How to Implement Protected Routes in React Router DOM v5 and v6?

How to Create a Protected Route with React Router DOM?

Problem

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;
Copy after login

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"));
  }
}
Copy after login

Solution

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 }} />;
}
Copy after login

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>
Copy after login

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 }
      }}
    />
  );
};
Copy after login

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 (
    ...
  );
}
Copy after login

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>
  );
}
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template