简体   繁体   中英

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 more streamlined solution, which necessarily doesn't demand the client browser to know all possible states for different roles prior to authentication?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM