Today, I'll be showing you Conditional Rendering in React.js.
Conditional Rendering is to Render Components based on Conditions.
For Example:
if(Condition A == true){
return <Component_A/>;
}
else{
return <Component_B/>;
}
In React, this can be done in 3 ways.
First, Using the good old Ternary Operator.
Ternary Operator checks the given condition, and if it's true it returns the Element/Component next to the question mark (?) else it returns the Element/Component next to Colon (:).
Syntax of Ternary Operator.
Condition ? return if true : return if false
Example
const Component_Temp=(props)=>{
return(
<div>
{ A === B?
<Component_A/>:
<Component_B/> }
</div>
);
}
export default Component_Temp;
Another way would be using Short-Circuit AND (&&) Operator.
Here in this method, a Condition is given on the left-hand side of the Logical AND (&&), if it's true then the right-hand side is evaluated and the Element/Component specified there is rendered.
Syntax of Short-Circuit AND (&&) Operator.
Condition && Evaluated if true
Example
const Component_Temp=(props)=>{
return(
<div>
{A === B && <Component_A/>}
{A !== B && <Component_B/>}
</div>
);
}
export default Component_Temp;
Ok now the last one, this is my personal favorite. Using React Element Variables.
In this method, we define a variable with an HTML or React Element/Component and if the specified condition will be true, we will change the content of that variable.
Example
const Component_Temp=(props)=>{
let componentToDisplay = <p>Content</p>;
if(A === B){
componentToDisplay = <Component_A/>
}
else if(A !== B){
componentToDisplay = <Component_B/>
}
return (
<div>
{componentToDisplay};
</div>
);
}
export default Component_Temp;
Being a Fan of Leaner JSX code snippet, I like this approach. It makes the JSX look cleaner and less confusing because the conditions are checked outside it.
If this blog helped you, please give it a thumbs up๐.
Thank you.