Private Routing In React-JS

Hello developers, today we are going to learn the most essential topic of the website which is private routing

what is private routing?

if a user is not authenticated and wants to access a specific page they cannot access it

First, create a project using the following command

npx create-react-app private-routing

Then you need to install react-router and react-router-dom in your project

npm i react-router-dom
npm i react-router

Then make a component called router.js or you can add routing in the app.js

import { BrowserRouter as Router, Route, Routes } from 'react-router-dom';
import { Navigate, Outlet } from 'react-router';
import './App.css';
import Login from './Components/Login';
import Admin from './Components/Admin';

function App() {
  const Auth = () => {
    if (!localStorage.getItem('userData')) {
      return <Navigate to='/' replace /> //Navigates user to login page if not logged in
    }
    else {
      return <Outlet /> //Outlet Renders the child route's element, if there is one.
    }
  }
  return (
    <div className="App">
      <Router>
        <Routes>
          <Route path="/" element={<Login />} />
          <Route path='/' element={<Auth />} >
            <Route path="/admin" element={<Admin />} />
          </Route>
        </Routes>
      </Router>
    </div>
  );
}

export default App;

Demo:

Submit a Comment

Your email address will not be published.

Subscribe

Select Categories