DEV Community

Cover image for Conditional rendering in React
Samuel Lucas
Samuel Lucas

Posted on

Conditional rendering in React

Real quick, I have two components I want to render(show) based on the role of login status, if it's an admin then I want to display the admin UI or else if it's a user, display the user UI.
How do I do this?

Hello my dear reader, welcome to today's post where I'll be teaching the tricks and tips to solve the problem above. Enjoy you stay reading the post 📯.

When you have components you want to conditionally render, React has a way of helping you achieve that. Let's see it in action.

Let's use the problem above as an example. Say we have Admin & User components.

...
{
  return ({user && user.role === 
   "Admin" ? <Admin /> : <User />})
}
Enter fullscreen mode Exit fullscreen mode

So what's going on here. If a user is logged in, he's either having a role of User or Admin. Now we checked if there's a user, if there's one, check for the role and display the corresponding UI.

What about a situation where it's just a component you want to render?
Let's take a scenario where you want to display an error if password attempt's more than 3 times.

Simply do this in your return block:
Assume you have a variable called attempt holding the number of times the user tried logging in, and a component called ErrorToast that will display the error.

return({attempt >= 3 ? <ErrorToast /> : null})
Enter fullscreen mode Exit fullscreen mode

Here we are saying if the attempt is 3 times already, display the error if not, do nothing.

Or the easier way

return({attempt >= 3 && <ErrorToast />})
Enter fullscreen mode Exit fullscreen mode

And that's all for now.
If you did learn something, kindly share and give it a like 😉

Top comments (0)