DEV Community

loading...

Discussion on: React Clean Code Tricks Everyone Should Know...

Collapse
ecyrbe profile image
ecyrbe • Edited

About role management.

What is shown here is a bad practice.

Indeed, in role based systems, roles are not static components. Roles are defined dynamically at runtime by business owners.

They affect rights to roles, create new roles, delete some, update others...

What you as a programmer should rely on is a set of rights the user have.

If a user has the right to edit a content, show him a 'edit' Button, etc...

Do not make giant opaque components that are role based oriented, make small ones that are rights based oriented.

Collapse
guruprasaths profile image
guruprasath-s

Hi,
Please help me with some examples code for role based rendering and authorization

Collapse
ecyrbe profile image
ecyrbe

Hello,
If you really are into programming, you should never ask things like that.

Really you should try, test and ask your peers for review. It's the best way to learn.

Nevertheless, here are some suggestions on how to achieve permission based react components.

First never make your basic components permission oriented. Second, try to create either :

  • a custom HOC withRights() that take one or multiples rights to check and a component to return if the rights are ok.
  • a react custom Hook useRights() that take one or multiples rights and return if the connected user is authorised or not.
  • a middleware component 'Rights' that take rights as props and components as childs to render if the connected user as the corresponding rights.

You'll be able to apply it to every business logic that require permissions. For permission based components, i prefer using the component based pattern instead of Hooks or HOC. But all are ok.

This might look like this :

 <Rights allow="list.edit">
   <Button>Edit</Button>
 </Rights>
Enter fullscreen mode Exit fullscreen mode
Collapse
sudarshansb143 profile image
sudarshan Author

Thanks for feedback.

I agree with you on the dynamic nature of the roles.

But, here I focused on the small app which mainly contains two/three types of users

i.e. normal and admin level

Hence, i designed the code in that way !

anyways i will remember your feedback and will take care of it next time :)