Loop through multiple routes as a way to simplify your react router implementation
import React from 'react';
import { Route, Switch, useLocation } from "react-router-dom";
import ProtectedRoute from './utils/ProtectedRoute';
const About = React.lazy(() => import("./components/pages/About"))
const Contact = React.lazy(() => import("./components/pages/Contact"))
const Home = React.lazy(() => import("./components/pages/Home"))
const Login = React.lazy(() => import("./components/pages/Login"))
const Dashboard = React.lazy(() => import("./components/pages/Dashboard"))
const PageNotFound = React.lazy(() => import("./components/pages/PageNotFound"))
const Routes = () => {
const location = useLocation();
const routes = [
{ component: Home, security: 'public', path: '/' },
{ component: About, security: 'public', path: '/about' },
{ component: Contact, security: 'public', path: '/contact' },
{ component: Login, security: 'public', path: '/login' },
{ component: Dashboard, security: 'private', path: '/dashboard' }
];
// Fallback route
routes.push({ component: PageNotFound, security: 'public', path: '*' })
return (
<React.Suspense fallback={<AppLoader />}>
<Switch location={location} key={location.pathname}>
{routes.map((route, key) => {
return (
route.security === "public" ?
<Route exact key={key} path={route.path} component={route.component} /> :
<ProtectedRoute exact key={key} path={route.path} component={route.component} />
)
})}
</Switch>
</React.Suspense>
);
};
export default Routes;
Protected Routes Implementation - referer to https://gist.github.com/garikaijenje/58f4aebc7b0661222c7b5d37bc8241fb