React Conditional Rendering
From the given scenario, we can understand how conditional rendering works. Consider an example of handling a login/logout button. The login and logout buttons will be separate components. If a user logged in, render the logout component to display the logout button. If a user not logged in, render the login component to display the login button. In React, this situation is called as conditional rendering.
There is more than one way to do conditional rendering in React. They are given below.
It is the easiest way to have a conditional rendering in React in the render method. It is restricted to the total block of the component. IF the condition is true, it will return the element to be rendered. It can be understood in the below example.
Logical && operator
This operator is used for checking the condition. If the condition is true, it will return the element right after &&, and if it is false, React will ignore and skip it.
We can understand the behavior of this concept from the below example.
If you run the below code, you will not see the alert message because the condition is not matching.
If you run the below code, you will see the alert message because the condition is matching.
You can see in the above output that as the condition (10 > 5) evaluates to true, the alert message is successfully rendered on the screen.
The ternary operator is used in cases where two blocks alternate given a certain condition. This operator makes your if-else statement more concise. It takes three operands and used as a shortcut for the if statement.
If the condition is true, statement1 will be rendered. Otherwise, false will be rendered.
Switch case operator
Sometimes it is possible to have multiple conditional renderings. In the switch case, conditional rendering is applied based on a different state.
Conditional Rendering with enums
An enum is a great way to have a multiple conditional rendering. It is more readable as compared to switch case operator. It is perfect for mapping between different state. It is also perfect for mapping in more than one condition. It can be understood in the below example.
Conditional Rendering Example
In the below example, we have created a stateful component called App which maintains the login control. Here, we create three components representing Logout, Login, and Message component. The stateful component App will render either
When you execute the above code, you will get the following screen.
After clicking the logout button, you will get the below screen.
Preventing Component form Rendering
Sometimes it might happen that a component hides itself even though another component rendered it. To do this (prevent a component from rendering), we will have to return null instead of its render output. It can be understood in the below example:
In this example, the