Tuomas Toivonen
Tuomas Toivonen

Reputation: 23502

React Application and User Roles

Is there a "built in" way to scope with different user roles in React Application? I want certain tabs, menus and links (routes) to be available only for certain users and not for others. Also, the content and options of many views will vary depending on the role. I know how to manage roles in the back end and retrieve them during the authentication in the JWT token, but what is the best way to parametrize the client-side state and representation based on the roles? Is the Redux and render logic conditions way to go, or is there a more streamlined solution, which necessarily doesn't demand the client browser to know all possible states for different roles prior to authentication?

Upvotes: 3

Views: 837

Answers (1)

hannad rehman
hannad rehman

Reputation: 4341

I can suggest write a higher order component which takes roles who can see the feature.

const AuthorizeOnly = ({ children, allowedRoles, user }) => (
  allowedRoles.includes(user.role)
  && (
  <React.Fragment>
    {children}
  </React.Fragment>
  )
);

// some component

loggedInUser = {
  name:'john',
  role:'admin' 
}
render(){
   <div>
     <AuthorizedOnly allowedRoles={['admin']} user={loggedInUser}>
       <p>only admin can see this.</p>
      </AuthorizedOnly>
   </div>
 }

You can tweak the logic inside AuthorizedOnly component based on your business logic.

For Router you can use the similar component which returns a Route based on your condition

Upvotes: 2

Related Questions