React Conditionals
React allows you to conditionally render components.
There are various ways to accomplish this.
if Statement
We can use the if JavaScript operator to determine which component to render.
Example
We’ll use the following two components:
function MissedGoal() {
return MISSED!
;
}
function MadeGoal() {
return Goal!
;
}
Example
Now, we’ll make another component that determines which component to render based on a condition:
function Goal(props) {
const isGoal = props.isGoal;
if (isGoal) {
return ;
}
return ;
}
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render( );
Try setting the isGoal attribute to true.
Example
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render( );
Logical && Operator
Another method for conditionally rendering a React component is to use the && operator.
Example
We can incorporate JavaScript expressions in JSX using curly braces:
function Garage(props) {
const cars = props.cars;
return (
<>
Garage
{cars.length > 0 &&
You have {cars.length} cars in your garage.
}
>
);
}
const cars = ['Ford', 'BMW', 'Audi'];
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render( );
If cars.length > 0 equals true, the expression after && will be rendered.
Try emptying the cars array.
Example
const cars = [];
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render( );
Ternary Operator
Another method for conditionally rendering components is to use a ternary operator.
condition ? true : false
We shall return to the goal example.
Example
Return the MadeGoal component if isGoal is true; else, return the MissedGoal component.
function Goal(props) {
const isGoal = props.isGoal;
return (
<>
{ isGoal ? : }
>
);
}
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render( );