![]() |
VOOZH | about |
In React, conditional rendering helps show different things based on certain conditions. The ternary operator is a concise way to do this quickly and clearly. In this article, we will learn step by step process to use the ternary operator for conditional rendering in React.
Syntax: React developers have multiple approaches for implementing conditional rendering, but the ternary operator stands out for its concise syntax.
condition ? expression_if_true : expression_if_false;Different approaches discussed below:
Table of Content
the basic form of the ternary operator is used to assign a value based on a condition. Here's a simple example:
const result = condition ? 'True Value' : 'False Value';In this case, if the condition is true, the variable result will be assigned the value 'True Value'; otherwise, it will be assigned 'False Value'.
This approach showcases the ternary operator within JSX, a common scenario in React components for conditional rendering.
Syntax:
return (
<div>
{
isLoggedIn ? <p>Welcome, User!</p> :
<button
onClick={() => setLoggedIn(true)}>
Log In
</button>
}
</div>
);
Here, if isLoggedIn is true, it renders a welcoming message; otherwise, it displays a login button. This concise syntax is a powerful way to handle dynamic content in React components.
Step 1: Create a ReactJS project:
npx create-vite@latest conditional-rendering-app --template reactStep 2: Navigate to the project:
cd conditional-renderingStep 3: Installing the modules:
npm installThe updated dependencies in package.json file will look like:
"dependencies": {
"react": "^18.2.0",
"react-dom": "^18.2.0"
},
Example: Below is the code example of the ternary operator in conditional rendering:
Steps to run the app:
npm run startOutput: