Search code examples
reactjsreact-router

How to disable a route based on a condition


I have a route set up for a menu

import React from 'react';
import { Route, Routes, Navigate } from 'react-router-dom';
import { SalesOverviewNewPage } from "./inner-components";

export const DashboardPage = (props) => {
  return (
    <div className="flexRow full p-0 m-0">
      <div className='full-flex flexCol width100 p-0 m-0'>
        <Routes>
          <Route path="/" element={<Navigate replace to="sales-overview-new" />} />
          <Route path="/sales-overview-new" element={<SalesOverviewNewPage />} />
          <Route path="/devices-overview" element={null} />
          <Route path="/perfomance" element={null} />
          <Route path="/sales-datewise" element={null} />
          <Route path="/top-items-more" element={null} />
        </Routes>
      </div>
    </div>
  )
}

i need to make the menu items which doesn't have a component available to be still present in the submenu but to become disabled sort of based on a condition which isa always same.In the above code for which ever route that has null value as element i need to disable it. Is there a way to do this instead of removing the routes which has null value as elements.


Solution

  • A simple solution is to create a route object and use it in both places DashboardPage and Navigation.

    Create an object of your routes like below:

    const routes = [
      {
        text: '',   //this will be the link text
        component: <Navigate replace to="sales-overview-new" />,   // Or keep this null
        path: '/',
      },
      {
        text: 'Sales Overview New',   //this will be the link text
        component: <SalesOverviewNewPage />,   // Or keep this null
        path: '/sales-overview-new',
      },
      {
        text: 'Sales Overview New',   //this will be the link text
        component: null,   // Or keep this null
        path: '/sales-overview-new',
      }
    ]
    

    Next, import these routes in the DashboardPage and create Routes like this:

    <Routes>
      routes.map(route => (
        //I am using the key as routes.path as most of the times it will be unique, you can use index or any other value.
        <Route key={routes.path} path={routes.path} element={routes.component} />
      ));
    </Routes>
    

    Then, import and use the same routes object while rendering the links:

    <nav>
      routes.map(route => (
        route.component !== null ? 
          //Normal link  : 
          //Disabled link
      ));
    </nav>
    

    Modify and style disabled link and normal links as per your requirements.