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 😉

Heroku

Simplify your DevOps and maximize your time.

Since 2007, Heroku has been the go-to platform for developers as it monitors uptime, performance, and infrastructure concerns, allowing you to focus on writing code.

Learn More

Top comments (0)

SurveyJS custom survey software

JavaScript Form Builder UI Component

Generate dynamic JSON-driven forms directly in your JavaScript app (Angular, React, Vue.js, jQuery) with a fully customizable drag-and-drop form builder. Easily integrate with any backend system and retain full ownership over your data, with no user or form submission limits.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay