简体   繁体   中英

How to do nested conditional rendering in React?

A situation I have not ran into before due to way roles/authentication work in a project I am working on. On login, the code returns whether the user is just a user or an admin and renders the appropriate components, BUT if the user is an admin, I then need to conditionally evaluate API call returns and the type of category when someone searches. The data return from the box will be rendered in a component. There are three data types: user, group, account and these category values are retrieved from state with each API call return type. (user, group, account) Have to render different layouts for each of the 3 return data payloads.

Also, conditional rendering in the JSX page might be not the appropriate way to approach this, and please feel free to suggest a completely (and hopefully more elegant) way of doing something like this?

{isAdmin &&
  {isCategory === 'user'
     <User />
  }
  {isCategory === 'group'
     <Group />
  }
  {isCategory === 'account'
      <Account />
  }
}
 
{isUser &&
  <User />
}

Maybe clearer way is to create render function

const renderAdmin = () => {
  switch(isCategory) {
    case 'user':
      return <User />
    case 'group':
      return <Group />
    case 'account':
      return <Account />
    default:
      return null;
  }
}

and then in render

  <>
    {isUser &&  <User />}
    {isAdmin && renderAdmin()}
  </>

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