React Conditional Rendering: Mastering Dynamic UIs

Chidume Kenneth
5 min readJul 28, 2023

Conditional rendering is used in React to control which element(s) or component(s) should be displayed based on certain conditions. Instead of rendering all components or elements at once and then using CSS to hide and unhide them as the case maybe, which by the way is time consuming and requires more code!. Conditional rendering plays a crucial role in building dynamic user interfaces (UIs) that adapt and change based on user input, data, or application state. This makes us write less and concise code. In this article, we will look into how to make use of conditional rendering in React and its various techniques.

Understanding Conditional Rendering

Just as I said earlier, Conditional rendering allows one to display components or elements selectively, depending on certain conditions. These conditions may rely on factors such as the application’s state, user input, prop values, or any other variables or expressions.

In React, you commonly use conditional statements such as if else, ternary expressions, and logical && and logical || operators to achieve this. We will look at how to make use of each of them for conditional rendering in react:

If-else( if{}else{} )

if-else is a conditional statement we all know too well, it can be used to conditionally render components in react. Below is an example:

import React, {useState} from 'react';

function Login() {
const [isLoggedIn, setIsLoggedIn] = useState(false);
if (isLoggedIn) {
return <h1>Welcome back!</h1>;
} else {
return <h1>Please sign in.</h1>;
}
}

export default Login;

//Output: Please sign in.

In the above example, the Login component renders different headings based on the value of the “isLoggedIn” state. “isLoggedIn” state is initially set to false, that means initially the header 1 (<h1>) tag with text “Please sign in.” will be displayed, until “isLoggedIn” is changed or changes to true. If we change the “isLoggedIn” state to true , it now displays “Please sign in.” So this means that the element or component inside the if block will always be displayed whenever the given condition(in this case a state) is true, whereas the element or component inside the else block will be displayed whenever the condition or state is false.

Ternary Operator( condition ? case1:case2 )

The ternary operator is a simpler way to perform conditional rendering in React. It is commonly used for simple conditional statements. The ternary operator is called so because it takes three operands or arguments. “condition ? case1 : case2in this case the condition, case1 and case2 are the operands or operators. Whenever the condition evaluates to true, “case1” or the first expression is run or displayed (as in our case), otherwise “case2” or second expression is run or displayed. The ternary operator is confusing sometimes, but let us look at an example and understand how it is used with conditional rendering:

import React, {useState} from 'react';

function Greeting() {
const [isLoggedIn, setIsLoggedIn] = useState(true);
return isLoggedIn ? <h1>Welcome back!</h1> : <h1>Please sign in.</h1>;
}

export default Greeting;
//Output: Welcome back!

In the above example the isLoggedIn state is set to true initially, that means the first element (<h1>Welcome back!</h1>) is displayed. Whenever it is set to false the second element (<h1>Please sign in.</h1>) will be displayed. I think this looks simpler than using if else!. Let us look at a sample code when the condition is false:

import React, {useState} from 'react';

function Greeting() {
const [isLoggedIn, setIsLoggedIn] = useState(false);
return isLoggedIn ? <h1>Welcome back!</h1> : <h1>Please sign in.</h1>;
}

export default Greeting;
//Output: Please sign in.

In the above example, “isLoggedIn” state is changed to false, therefore the second element inside the ternary operator is displayed which in this case is : “Please sign in”.

It is advisable to use brackets to wrap each expression, element or component of a ternary operator to avoid confusion, just as shown in the example below:

import React, {useState} from 'react';

function Greeting() {
const [isLoggedIn, setIsLoggedIn] = useState(false);
return isLoggedIn ? (<h1>Welcome back!</h1> ) : (<h1>Please sign in.</h1> );
}

export default Greeting;
//Output: Please sign in.

Wrapping the elements, components or expressions (as the case maybe ) with brackets helps avoid confusion especially when the expressions is too much.

Logical && Operator( && )

The logical “&&” operator allows us to conditionally render a component based on a simple condition. it only renders whenever the given condition is true otherwise nothing is rendered, that means if the condition is false, the component won't be rendered at all. This is normally used whenever you want to render a component or an element only when a given condition is true and you don’t want to render or do any other thing when it is false. Let us look at an example below:

import React,{useState} from 'react';

function UserDetails() {
const[user, setUser] = useState({
name:"Kenneth",
email:"Kennethnebolisa@gmail.com" });
return (
<div>
{user && (
<div>
<h2>{user.name}</h2>
<p>Email: {user.email}</p>
</div>
)}
</div>
);
}

export default UserDetails;

Looking at the above example the condition given to the logical && operator is a state whose initial value is an object. So whenever this state is truthy, the div that will display the user name(in this case “Kenneth”) and email(“Kennethnebolisa@gmail.com”) will be displayed, otherwise an empty div is rendered. This is a useful technique when you want to avoid rendering elements with missing or undefined data.

Logical || Operator( || )

The logical || operator can be used to provide a default value when a certain condition is not met or false: Below is an example:

import React from 'react';

function UserProfile({ user }) {
const defaultUser = { name: 'Guest', email: 'guest@example.com' };
const currentUser = user || defaultUser;

return (
<div>
<h2>{currentUser.name}</h2>
<p>Email: {currentUser.email}</p>
</div>
);
}

export default UserProfile;

In the above example, the “currentUser” variable is only set to “defaultUser” whenever the “user” prop is falsy. But as far as the “user” prop is truthy it will always be rendered. The logical || operator works like this: It first checks the condition of the first expression given to it(expression at it’s right side), if it is true then it uses it, but if it is false it then makes use of the second expression(at it’s left side). This is unlike the the logical && operator which renders only when the given condition is true and does nothing when false.

Switch Statement

The switch conditional rendering is used when you have more complex conditional rendering scenarios. For example, when you have multiple conditions with different possible outcomes and you need to render an element or component based on any of the outcomes. Here’s an example:

import React from 'react';

function OrderStatus({ status }) {
switch (status) {
case 'pending':
return <p>Your order is pending.</p>;
case 'shipped':
return <p>Your order has been shipped.</p>;
case 'delivered':
return <p>Your order has been delivered.</p>;
default:
return <p>Invalid order status.</p>;
}
}

export default OrderStatus;

From the example above, switch statement is used to specify which element to render based on the value of a prop called “status” passed to it. This means that when the “status” value is “pending”, the <p> tag with text “Your order is pending.” will be render, when it is “shipped” the <p> tag with text “Your order has been shipped” will be rendered and so on.

Conclusion

In this article, we explored various techniques for conditional rendering, including if-else statements, ternary operators, logical && and || operators, and the switch statement. Understanding these techniques will allow you to build more flexible and user-friendly React applications.

--

--