How to use conditional rendering in ReactJS?
There are several ways you can render conditionally with React.
We can render using the if
Statement
We can use the if
JavaScript operator to decide which component to render.
Code Sample:
function Goal(props) {
const isGoal = props.isGoal;
if (isGoal) {
return <MadeGoal/>;
}
return <MissedGoal/>;
}
ReactDOM.render(
<Goal isGoal={false} />,
document.getElementById('root')
);
Another way to conditionally render a React component is by using the Logic &&
operator.
import React from 'react';
import ReactDOM from 'react-dom';
function Garage(props) {
const cars = props.cars;
return (
<>
<h1>Garage</h1>
{cars.length > 0 &&
<h2>
You have {cars.length} cars in your garage.
</h2>
}
</>
);
}
const cars = ['Ford', 'BMW', 'Audi'];
ReactDOM.render(
<Garage cars={cars} />,
document.getElementById('root')
);
If cars.length
equates to true, the expression after &&
will render.
Lastly, another way to conditionally render elements is by using a ternary operator.
If the condition ? true : false
.
Code Sample:
function Goal(props) {
const isGoal = props.isGoal;
return (
<>
{ isGoal ? <MadeGoal/> : <MissedGoal/> }
</>
);
}
ReactDOM.render(
<Goal isGoal={false} />,
document.getElementById('root')
);
If the first condition is met <MadeGoal/>
will be rendered else <MissedGoal/>
will be rendered as alternative.