Home > Blockchain >  How to do role based access routing in react
How to do role based access routing in react

Time:09-02

I want to give permissions to some pages to users, some more pages access to manager and all pages access to admin.

if user admin loggedin

const role = 'admin'
{role === 'admin' ? (
    <>    
      <Route path='/' component={Home} />
      <Route path='/products/' exact={true} component={Products} />
 <Route path='/products-edit' exact={true} component={ProductsEdit} />
<Route path='/all-products' exact={true} component={AllProducts} />
</>
)}

if user manager loggedin

{role === 'manager' ? (
    <>    
      <Route path='/' component={Home} />
      <Route path='/products/' exact={true} component={Products} />
 <Route path='/products-edit' exact={true} component={ProductsEdit} />
</>
)}

if user logged in

{role === 'user' ? (
    <>    
      <Route path='/' component={Home} />
      <Route path='/products/' exact={true} component={Products} />
</>
)}

CodePudding user response:

Is the code working and you what you need is to simplify the code? If so, and you have only 3 roles, then I guess the below code would also work as the same as your code and also reduce the lines of code.

<Route path='/' component={Home} />
<Route path='/products/' exact={true} component={Products} />
{role !== 'user' && <Route path='/products-edit' exact={true} component={ProductsEdit} />}
{role === 'admin' && <Route path='/all-products' exact={true} component={AllProducts} />

CodePudding user response:

You can create a special RoleRoute component that takes an array of roles that have access to that route, and check this against the current role value a user has. If the user has an appropriate role then they can access the route, otherwise render a redirect off the route.

Example:

const RoleRoute = ({ role, roles = [], ...props }) => {
  return !roles.length || roles.includes(role) ? (
    <Route {...props} />
  ) : (
    <Redirect to=".." />
  );
};

...

<Switch>
  <RoleRoute
    path="/products"
    role={role}
    roles={["admin", "manager", "user"]}
    component={Products}
  />
  <RoleRoute
    path="/products-edit"
    role={role}
    roles={["admin", "manager"]}
    component={ProductsEdit}
  />
  <RoleRoute
    path="/all-products"
    role={role}
    roles={["admin"]}
    component={AllProducts}
  />
  <Route path="/" component={Home} />
  <Redirect to="/" />
</Switch>

Demo

Edit how-to-do-role-based-access-routing-in-react

  • Related