DEV Community

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

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