In this article, we are going to examine multiple ways to implement conditional rendering in React applications.
Conditional rendering in React works the same way conditions work in JavaScript. Use JavaScript operators like if
, else
or the conditional operator to create elements representing the current state, and let React update the UI to match them.
Using if statements would be the simplest way to implement conditional rendering in React JS.
Let’s take a look at this example where we show a welcome message to the user if he is logged in 🔍👀
First, let’s create two functional components, one component returns the message “Hello world” and the other “Welcome user 007”.
Now let’s create a third functional component that takes in the two previous components and using an if
statement we are going to check if the user is logged in or not and return the corresponding message.
The next thing we are gonna cover is how to do conditional rendering using the switch case.
There are a couple of reasons you might prefer to use switch case
instead of if
:
For the next example let’s create an error component that takes in a string value and returns an error message based on the value of the props we pass.
Element variables are simply variables that hold JSX elements. By using variables to store components or some values we can render a part of the component while the rest of the output doesn’t change.
Let’s take a look at the following code so that you can understand what I mean.🔍👀
Here we are using the two previously created functional components, we are gonna assign one of them to a variable depending on the value we get from the props we pass to the IsUserLoggedIn component:
It’s true that we can use JavaScript in JSX, but it becomes difficult when using statements like if
, else
, and switch case
within JSX. There is no real way to inline it.
If you are familiar with ternary operators, then you are aware that it is simply a more concise way to write an if
statement. Thus we have:
The parentheses () around both implicit return statements in the ternary operator enable you to return single or multiple HTML elements or React components from there. If it’s just a single element though, you can omit the parentheses.
The ternary operation makes the conditional rendering in React not only more concise but gives you an easy way to inline the conditional rendering in your return. This way, only one part of your JSX is conditionally rendered, while other parts can stay intact without any condition.
The logical &&
operator helps you to make conditions that would return null more concise. In JavaScript, a true && ‘Loading…’ always evaluates to ‘Loading…‘.
Let’s take a look at our next example where we display ‘Loading…’ if the isLoading props is equal to true or ‘Hello world!’ if it is false:
I hope this React tutorial was helpful for you to learn about conditional renderings. If you liked it, please share it with your friends.
Quick Links
Legal Stuff