Conditional Rendering in React
Documentation on React describes conditional rendering as using the conditional to create elements representing the current state, and then updating the UI. Here is an example of a function rendering two different components based off the isLoggedIn state from Reactjs.org.
As you can see, the Greeting function takes in a prop, isLoggedIn, and then renders either UserGreeting or GuestGreeting based on the prop. In this code, the prop is shown as false, and will render the GuestGreeting based on the conditional.
Although the above method is one way to render something conditionally, but, it uses a functional component to render. This may pose an issue for someone trying to render something in a Class component. Due to the render() inside of a Class component, it is impossible to put an if statement inside the render. However, React is able to use a ternary in these situations.
The ternary is also known as the Conditional Operator. According to Mozilla Developer Network, the ternary syntax is written like below.
The condition in the above code is the expression that will return a Boolean value. The (?) operator signals the end of the conditional statement. The (:) is the divider between what should be returned based off the Boolean. If it is true, the left-side of the colon will be returned and if it is false, the right-side is returned. This is the basic way a ternary is used.
Using the Ternary in React
The advantage of using the Conditional Operator is that it can be used within the render() in a Class Component. The only difference is that the entire statement must be put into brackets. Here is an example of the syntax when inside of the render().
Here, the Boolean value of the Ternary is false as indicated by the state “exp”. The false value means the right-side of the statement will be returned, which means the console will log a string of false as indicated in the second picture.
In the code below, the next two images shows how instead of a console log, we can actually render HTML elements.
Now that we switched the value of “exp” to true, the left-side of the semi-colon is now returned. Here, I made a simple h1 element with True as the heading. The next step would be to render components within the conditional. The code below has a button, that when clicked, will change the value of the Boolean in the ternary. The webpage reflects this change by rendering a different component.
The ternary is a powerful tool that can make a developers webpage more dynamic. There are many different situations in which this syntax can be used. A webpage may have many different components that will render based off the state of an app. By using ternaries, quick and easy code can be manipulated to render the correct elements. For further information, please follow the links to go to the React Documentation on conditional rendering.