Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save garikaijenje/9a46d44daf0c45525a5d83108b1b13af to your computer and use it in GitHub Desktop.
Save garikaijenje/9a46d44daf0c45525a5d83108b1b13af to your computer and use it in GitHub Desktop.
React Router - Refactor Multiple Routes

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment