0

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/>
}
...

]

  • Does this answer your question? [How to implement authenticated routes in React Router 4?](https://stackoverflow.com/questions/43164554/how-to-implement-authenticated-routes-in-react-router-4) – Antonio Erdeljac Oct 09 '20 at 15:33
  • @Antonio no it doesn't. I am using react router 6 useRoutes function. What is answered is when you are using the normal router functions. My routes are in an object – Clinton Mwachia Oct 11 '20 at 12:09

1 Answers1

0

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
        );
}
 
Namzz
  • 11
  • 1