Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR JAVASCRIPT

how to protect routes in react router v6

/*
|==================================================
| METHOD 1 -- 
|==================================================
*/

//======= ProtectedRoute.js File =========
import React from "react";
import { Navigate } from "react-router-dom";

function ProtectedRoute({ children }) {

    const isLogin = localStorage.getItem("isLogin");
    console.log("Is User Login?", isLogin);

    return (
        isLogin ? children : <Navigate to="/login" />
    );
}

export default ProtectedRoute;


//========== App.js File ===========
<Route path="/admin" element={<AdminMaster />}>
		  
  	// PROTECTED ROUTE
  	<Route
        path="/admin/dashboard"
        element={
            <ProtectedRoute>
            <Dashboard />
            </ProtectedRoute>
        }
	/>
    
    // PUBLIC ROUTES
    <Route path="/admin/profile" element={<Profile />} />
    <Route path="/admin/users" element={<Users />} />
    <Route path="/admin/categories" element={<Categories />} />
    <Route path="/admin/brands" element={<Brands />} />
    <Route path="/admin/products" element={<Products />} />
    <Route path="/admin/orders" element={<Orders />} />
 </Route>
 
PREVIOUS NEXT
Tagged: #protect #routes #react #router
ADD COMMENT
Topic
Name
2+1 =