Reputation: 465
Have created a react js dashboard app with the following versions "react-router": "^6.0.0-beta.0", "react-router-dom": "^6.0.0-beta.0"
have to implement a protected routing instance for the app, as of react router v6 above protected routing is a bit different than i'm used to on v5. could someone show me how to add protected routing for this? Thank you for your time!
here's the app.js
import 'react-perfect-scrollbar/dist/css/styles.css';
import React from 'react';
import { useRoutes } from 'react-router-dom';
import { ThemeProvider } from '@material-ui/core';
import GlobalStyles from 'src/components/GlobalStyles';
import 'src/mixins/chartjs';
import theme from 'src/theme';
import routes from 'src/routes';
const App = () => {
const routing = useRoutes(routes);
return (
<ThemeProvider theme={theme}>
<GlobalStyles />
{routing}
</ThemeProvider>
);
};
export default App;
and here is the route.js code
const routes = [
{
path: 'app',
element: <DashboardLayout />,
children: [
{ path: 'account', element: <AccountView /> },
{ path: 'reporting', element: <CustomerListView /> },
{ path: 'dashboard', element: <DashboardView /> },
{ path: 'classrooms', element: <ProductListView /> },
{ path: 'settings', element: <SettingsView /> },
{ path: '*', element: <Navigate to="/404" /> }
]
},
{
path: '/',
element: <MainLayout />,
children: [
{ path: 'login', element: <LoginView /> },
{ path: 'register', element: <RegisterView /> },
{
path: 'RegisterViewContactDetails',
element: <RegisterViewContactDetails />
},
{ path: 'ForgotPassword', element: <ForgotPassword /> },
{ path: 'RestPassword', element: <RestPassword /> },
{ path: '404', element: <NotFoundView /> },
{ path: '/', element: <Navigate to="/login" /> },
{ path: '*', element: <Navigate to="/404" /> }
]
}
];
export default routes;
Upvotes: 3
Views: 5205
Reputation: 2525
Here is my working example for implementing protected routes by using useRoutes hook.
App.js
import routes from './routes';
import { useRoutes } from 'react-router-dom';
function App() {
const { isLoggedIn } = useSelector((state) => state.auth);
const routing = useRoutes(routes(isLoggedIn));
return (
<>
{routing}
</>
);
}
routes.js
import { Navigate,Outlet } from 'react-router-dom';
const routes = (isLoggedIn) => [
{
path: '/app', // protected routes
element: isLoggedIn ? <DashboardLayout /> : <Navigate to="/login" />,
children: [
{ path: '/dashboard', element: <Dashboard /> },
{ path: '/account', element: <Account /> },
{ path: '/', element: <Navigate to="/app/dashboard" /> },
{
path: 'member',
element: <Outlet />,
children: [
{ path: '/', element: <MemberGrid /> },
{ path: '/add', element: <AddMember /> },
],
},
],
},
{ // public routes
path: '/',
element: !isLoggedIn ? <MainLayout /> : <Navigate to="/app/dashboard" />,
children: [
{ path: 'login', element: <Login /> },
{ path: '/', element: <Navigate to="/login" /> },
],
},
];
export default routes;
Upvotes: 9