-1

I have a React application with React Router set up to handle navigation. In my application, I want to implement dynamic routing based on the user's role, where different pages are shown for the same route depending on the user's role. Currently, I have a working solution using a roleRedirect object that maps roles to corresponding paths, but I suspect there might be a more efficient and elegant way to achieve this functionality.

I would appreciate any guidance on how to improve this routing logic.

Below is the code snippet, ofcourse I would be using redux state to get user roles, but for the sake of simplicity I wrote this:

const roleRedirect = {
  admin: "/admin",
  agent: "/user",
};

const App = () => {
  let userRole = "admin";

  return (
    <ThemeProvider theme={theme}>
      <Routes>
        <Route path="/" element={<FullLayout />}>
          <Route path="/" element={<Navigate to={roleRedirect[userRole]} replace />} />
          <Route path="/login" element={<Login />} />

          <Route path="/admin" element={<AdminDashboard />} />

          <Route path="/user" element={<UserDashboard />} />
        </Route>
      </Routes>
    </ThemeProvider>
  );
};
Farooq Ali
  • 11
  • 1
  • 1
  • 4
  • If this is working for you then it seems fine to me. Are you just asking for potential optimizations? If so, then this question is likely a better fit for [Code Review](https://codereview.stackexchange.com/). – Drew Reese Aug 05 '23 at 22:41
  • Didn't know about this, thank you, I'll check this out. – Farooq Ali Aug 06 '23 at 11:58

1 Answers1

0

Maybe you could try something like this:

import { BrowserRouter, Navigate, Route, Routes } from "react-router-dom";

const isAdmin = true;

const AdminDashboard = () => {
  return <div>Admin Dashboard</div>;
};

const UserDashboard = () => {
  return <div>User dashboard</div>;
};

const Redirect = () => {
  return isAdmin ? (
    <Navigate to="/admin" replace />
  ) : (
    <Navigate to="/user" replace />
  );
};

export default function App() {
  return (
    <BrowserRouter>
      <Routes>
        <Route path="/" element={<Redirect />} />
        <Route path="/admin" element={<AdminDashboard />} />
        <Route path="/user" element={<UserDashboard />} />
      </Routes>
    </BrowserRouter>
  );
}

Klian
  • 1,520
  • 5
  • 21
  • 32
  • Well I certainly could do this however I was talking from performance perspective as the navigate takes some time, plus, there will be more roles. So if there is any way that I can make it more fast. – Farooq Ali Aug 05 '23 at 16:42
  • How much time is taking? – Klian Aug 05 '23 at 17:10
  • I would say this is objectively worse than OP's code since the `Redirect` component iterates each "if-else" branch for each user/route couplet which has (`O(n)`) versus the `O(1)` lookup code OP already has. – Drew Reese Aug 05 '23 at 22:49