0

Say I have an array that contains objects with route props like this and permission.

const myRoutes = [
  { route: '/',
  element: <Home/>
  permission: 'admin' },
  { route: '/',
  element: <About/>
  permission: 'agent' },
]

In this case, both Home and About component are Private route and it goes like

  <Routes>
    <Route path="/" element={<PermissionCheck />}>
      {myRoutes.map((route)=> ({
        <Route path={route.path} element={route.element} permission={permission}/>
      })}
    </Route>
  </Routes>

To make a permission check abstracted, I would like to check the permission with given permission prop to each route, <Home /> and <About /> in this case.

I have come up with one way to solve this by creating a hook that accepts permission and call it in each route element but is there any better way to do the same?

JunKim
  • 647
  • 7
  • 17
  • 1
    You effectively asked the same question as a comment to a post of mine. What, or whose, permissions are you checking here? Can you [edit] the post to include a more complete and comprehensive [mcve]? Does this help answer your question regarding protecting specific routes: https://stackoverflow.com/questions/66289122/how-to-create-a-protected-route? Or this one regarding protecting routes based on roles https://stackoverflow.com/a/73931932/8690857 or https://stackoverflow.com/a/73578811/8690857? – Drew Reese Jan 31 '23 at 06:59
  • Yes. I referred question you mentioned. The difference between that question and this is that each route under `` has its own permission given as a prop. So I ended up with like ``` myRoutes.map({route, element, permission})=> element} ``` – JunKim Feb 01 '23 at 02:45
  • A wrapper around each routed component would work. How many different permissions do users have in your app? – Drew Reese Feb 01 '23 at 03:12
  • Nearly a dozen. Wrapping each routed component looks okay since there are not too many. – JunKim Feb 01 '23 at 03:34
  • Yikes, then yeah, per route seems ok. – Drew Reese Feb 01 '23 at 03:37

1 Answers1

0

you can pass permissions or user roles array into Permission component as props,

<Route element={<Persmissions allowedRoles={["admin", "agent"]} />}>
  <Route path="home" element={<Home />} />
  <Route path="about" element={<About />} />
</Route>

and then verify the currently logged-in users role with the provided props in the Permission component, this way you can manage a group of routes private and provide a different level of authorization to users based on their role.