cmoshe
cmoshe

Reputation: 369

How to make Protected routes from an object of routes?

I need your help.I want the user to access the dashboard, and other components only if they are logged in. The challenge is I have an object of routes and I don't know how to implement protected routes in this scenario. The routes are as follows. I am using react-router v6.

Const routes = [
{
Path:"/",
element:<Componen1/>
},
{
Path:"/dashboard",
element:<Componen1/>
},
{
Path:"/list",
element:<Component2/>
}
...

]

Upvotes: 0

Views: 630

Answers (1)

Namzz
Namzz

Reputation: 21

The simple way is use <Navigate /> in react-router-dom v6 to redirect to login if users are not logged in

const routes = [
        { 
          path: 'dashboard', 
          element: (
             <ProtectedRoute>
                 <DashboardView />
             </ProtectedRoute>
          ) 
       },
       {
          Path:"/list",
          element:(
             <ProtectedRoute>
                <ListComponent2/>
             </ProtectedRoute>
          ) 
       },
       {
          Path:"/login",
          element:(
             <PublicRoute>
                <LoginComponent/>
             </PublicRoute>
          ) 
       },
       ...other paths
    ]  

ProtectedRoute.js

import React from "react";
import { Navigate, useLocation } from "react-router-dom";
import { useAuth } from "src/hooks/useAuth";

export function ProtectedRoute({ children }) {
    const { isAuth } = useAuth();
    const location = useLocation();

    return isAuth ? (
        children
    ) : (
            <Navigate
                to="/login"
                state={{ from: location }}
            />
        );
}

PublicRoute.js

import React from "react";
import { Navigate, useLocation } from "react-router-dom";
import { useAuth } from "src/hooks/useAuth";

export function PublicRoute({ children }) {
    let { isAuth } = useAuth();
    let location = useLocation();

    return isAuth ? (
        <Navigate
            to="/dashboard"
            state={{ from: location }}
        />
    ) : (
            children
        );
}
 

Upvotes: 1

Related Questions