Protected routes in react-router-dom v6.0

Viewed 394

I have a react template and it uses react-router-dom v6.0.0 beta.The routing methods are different in this version than previous ones. I want to authenticate the request using auth.js function and render the appropriate page. In react-router v5 it just had to wrap the route in < ProtectedRoute > element.How can I get the same result in this approach ?

routes.js

export default function Router() {
  return useRoutes([
    {
      path: '/dashboard',
      element: <DashboardLayout />,
      children: [
        { path: '/', element: <Navigate to="/dashboard/app" replace /> },
        { path: 'app', element: <DashboardApp /> },
      ]
    },
    {
      path: '/',
      element: <LogoOnlyLayout />,
      children: [
        { path: 'login', element: <Login /> },
        { path: 'register', element: <Register /> },
        { path: '404', element: <NotFound / },
        { path: '/', element: <Navigate to="/dashboard" /> },
        { path: '*', element: <Navigate to="/404" /> }
      ]
    },

    { path: '*', element: <Navigate to="/404" replace /> }
  ]);
}

auth.js

function ProtectedRoute({ component: Component, ...restOfProps }) {
  const isAuthenticated = false;
  return (
    <Route
      {...restOfProps}
      render={(props) =>
        isAuthenticated ? <Component {...props} /> : <Redirect to="/login" />
      }
    />
  );
}

export default ProtectedRoute;

App.js

import Router from './routes';

export default function App() {
  return (
      <Router />
  );
}


0 Answers
Related