Clean Way to do multiple conditional rendering in react?

Viewed 31

Now I'm making some conditional rendering about user permission with react.

I know how to do conditional rendering in react, but wonder is there any fancy and readable way to do it.

Most general way would be

function Test(){
return 
  {hasPermissionA ? <ATitle/> :<BTitle/>}
  {hasPermissionB1? <AHead/> ? hasPermissionB2 ? <BHead/> : <CHead/>
}

Nasty thing about this is permissions that are related could be fragmented in some cases

Another way is to gather related component and make some enum or functions...

const permissioned = {
   A : { head: <A/>
         title:<A1/>
         body:<A1/>
       },
   B: {
        head:<BHead/>
        title:<Btitle/>
        body: <BBody/>
       },
    AB:{
        head: <BHead/>
        title: <ATitle/>
        body: <BBody/>
       }
}

return  
<> 
   {permission[type].head}
   {permission[type].title}
   {permission[type].body}
</>;

But this code seems really awful....

Other way could be quiet simple.

Just make new component about each type.

function AComponent(){
    return 
      <ATitle/>
      <AHead/>
      <ABody/>
}

But it seems that I would make too many files and there are additional codes because I have to gave props to each component...

Is there any fancy way?

1 Answers

Once I did it by writing a function for different conditions.

Here check this out. Let me know what you think of this.

codesandbox

Related