☰ See All Chapters |
Conditional Rendering in ReactJS
In React, it allows us to render elements or components based on a condition. Below are the ways used to render elements conditionally:
if statement.
Logical && Operator
Ternary Operator
if Statement
It happens when you decide to render either of two elements, which sometimes is a choice between rendering an element or nothing. The simplest usage of a conditional rendering can be expressed by an if-else statement in JSX.
function DemoComponent(props) { const displayLastName = false; if (displayLastName) { return ( <div> <h1>First Name: {props.firstName}</h1> <h1>Last Name: {props.lastName}</h1> </div> ); } else { return ( <div> <h1>First Name: {props.firstName}</h1> </div> ); } }
export default DemoComponent; |
function DemoComponent(props) { const displayLastName = true; if (displayLastName) { return ( <div> <h1>First Name: {props.firstName}</h1> <h1>Last Name: {props.lastName}</h1> </div> ); } else { return ( <div> <h1>First Name: {props.firstName}</h1> </div> ); } } export default DemoComponent; |
Logical && Operator
If the condition is true, the expression after the logical && operator will be the output. If the condition is false, React ignores the expression.
function DemoComponent(props) { const displayLastName = true; return ( <div> <h1>First Name: {props.firstName}</h1> {displayLastName && <h1>Last Name: {props.lastName}</h1>} </div> ); }
export default DemoComponent; |
function DemoComponent(props) { const displayLastName = true; return ( <div> <h1>First Name: {props.firstName}</h1> {displayLastName && <h1>Last Name: {props.lastName}</h1>} </div> ); }
export default DemoComponent; |
Ternary Operator
The above approach of logical && operator can be still simplified by using ternary operator as shown below:
function DemoComponent(props) { const displayLastName = true; return ( <div> <h1>First Name: {props.firstName}</h1> {displayLastName ? <h1>Last Name: {props.lastName}</h1> : null} </div> ); }
export default DemoComponent; |
function DemoComponent(props) { const displayLastName = false; return ( <div> <h1>First Name: {props.firstName}</h1> {displayLastName ? <h1>Last Name: {props.lastName}</h1> : null} </div> ); }
export default DemoComponent; |
All Chapters