Conditional rendering is a fundamental concept in React that allows us to display different UI elements based on specific conditions. It's an essential tool for building interactive and responsive applications that adapt to user actions and data changes. In this article, we'll explain the various techniques used in conditional rendering, how they work, and best practices we can follow to create effective and interactive user interfaces.
This article will assume you're familiar with HTML, CSS, and JavaScript, and that you know at least the basics of React and JSX. Ideally, you'll also be familiar with debugging tools such as React Developer Tools, which are invaluable for troubleshooting issues related to conditional rendering and visualizing the component state and props.
How to Implement Conditional Rendering in a React Application
Conditional rendering is a powerful tool used to dynamically show or hide UI elements based on certain conditions. This makes our applications more interactive and responsive, because it adapts to user actions and data changes. There are various methods we could use to render elements conditionally in react. They include:
To illustrate how these techniques work, we're going to build a navigation bar (navbar). A navbar usually has links to various sections of a web app. However, we want the link to our "Cart" page to be hidden from unauthenticated users. To do this, we'll create React components, define states, and applying conditional logic based on user login status.
Using an If-else Statement
If-else statements are control flow structures that allow us to execute different codes based on whether a condition tests true or false. They can be used to render components based on the result. Let’s look at how this works:
if( condition ){
The task to be done if the condition tests true
}
else {
Tasks to be done when the condition is tested false
}
Now, based on the scenario we gave earlier, we want the navbar to have an extra button if the user is logged in, but to remain in the normal state when the user is logged out. To do this, we're going to have a JSON object that stores the details of our users, including their login status:
{
"Users": [
{
"Name": "Yemi",
"Age": 23,
"cartProducts": ["Tote bag", "Sports Cap", "Trainers", "Joggers"],
"Status": "loggedIn"
},
{
"Name": "John",
"Age": 30,
"cartProducts": ["Laptop", "Mouse", "Keyboard"],
"Status": "loggedIn"
},
{
"Name": "Alice",
"Age": 25,
"cartProducts": ["Dress", "Shoes", "Bag"],
"Status": "loggedOut"
}
]
}
Next, we'll create a logic that checks the status of the user and renders the navbar based on the result of the condition:
const user = users[0]; // Assuming we want to check the status of the first user
if (user.status === "loggedIn") {
return <LoggedInNavbar />;
} else {
return <LoggedOutNavbar />;
}
In this code snippet, we access the user.status
property which has a loggedIn
variable. This variable is a Boolean value that indicates whether the user is logged in. Before checking the condition, we create a constant variable named user
and assign it the value of the first element (index 0
) from the users
array. Since users
is an array of user objects, this effectively extracts the login status of the first user object.
Now, let's look at a breakdown of how we made use of the if-else statement to render elements:
- The if statement takes a condition as its argument. In this case, the condition is
isLoggedIn
. - If the condition is true, the code inside the if statement is executed, which returns a View Cart button element in the navbar.
- If the condition is false, the code inside the else statement is executed, and this renders the navbar without the extra button.
This is one of the most common methods used to conditionally render elements based on conditions in React. However, it can make our code more verbose, especially when dealing with simple conditions. This is where the ternary operator comes in, as it's a more concise alternative.
Using a Ternary Operator
A ternary operator is also known as a conditional operator. It's a simpler way of writing an if-else statement. It has three parts:
condition ? trueExpression : falseExpression
- The
condition
is the part to be evaluated. - The
trueExpression
is to be executed if the condition is true. - The
falseExpression
is to be executed if the condition is false.
For instance, the previous code snippet we used to render different navbars can be written as follows using a ternary operator:
return ( <div> {user.status === "loggedIn" ? <LoggedInNavbar /> : <LoggedOutNavbar />}
</div>
);
};
export default App;
Just like in the previous scenario, if the condition is true, the expression LoggedInNavbar
is executed, rendering the LoggedInNavbar
component. Otherwise, the expression LoggedOutNavbar
is executed, rendering the LoggedOutNavbar
component.
When to use the ternary operator
The ternary operator is most suitable for handling simple conditional statements where we have two possible outcomes. However, it may be more appropriate to use an if-else statement for more complex conditional logic involving multiple conditions or nested statements.
Using the Logical AND Operator
An AND
operator is a logical operator used to evaluate more than one condition or expression. It accepts conditions and only tests as true when the two (or more) conditions are tested true.
For example, let's assume that we only want users who are registered as sellers and are logged in to access the navbar with a dashboard button:
const users = [
{
name: "Yemi",
age: 23,
cartProducts: ["Tote bag", "Sports Cap", "Trainers", "Joggers"],
status: "loggedIn",
userClass: "Admin",
},
];
const user = users[0]; // Assuming we want to check the status of the first user
if (user.status === "loggedIn" && user.userClass === "Admin") {
return <AdminNavbar />;
} else {
return <LoggedOutNavbar />;
}
In this code snippet, we are determining which navbar component to render based on the login status and user class of the first user in the users
array. It utilizes an if-else statement to check if both the user.status
and the user.userClass
properties meet the specified criteria. If both conditions are true, the code inside the if block is executed, returning the AdminNavbar
component.
This indicates that the logged-in user as an admin and should see the admin-specific navbar. If either or both conditions are false, the code inside the else block is executed, returning the LoggedOutNavbar
component. This indicates that the user is either not logged in or not an admin and should see the standard navbar.
The post 6 Techniques for Conditional Rendering in React, with Examples appeared first on SitePoint.