Loading lesson path
In React, you can conditionally render components. There are several ways to do this. if
JavaScript operator to decide which component to render.
function MissedGoal() {
return <h1>MISSED!</h1>;
}function MadeGoal() {
return <h1>Goal!</h1>;
}Now, we'll create another component that chooses which component to render based on a condition:
function Goal(props) {
const isGoal = props.isGoal;
if (isGoal) {
return <MadeGoal/>;
}
return <MissedGoal/>;
}createRoot(document.getElementById('root')).render(
<Goal isGoal={false} />
);Example »
createRoot(document.getElementById('root')).render(
<Goal isGoal={true} />
);Example »
&&
Another way to conditionally render a React component is by using the && operator. In the example below, the heading will only be rendered if the props.brand property is not empty:
&& will only be rendered if the left side is true:
function Car(props) {
return (<>
{props.brand && <h1>My car is a {props.brand}!</h1>}</>
);
}createRoot(document.getElementById('root')).render( <Car brand="Ford" />
);Example » If props.brand evaluates to true, the expression after && will render.
createRoot(document.getElementById('root')).render( <Car />
);Example »
Another way to conditionally render elements is by using a ternary operator. condition ? true : false We will go back to the goal example.
MadeGoal component if isGoal is true, otherwise return the
function Goal(props) {
const isGoal = props.isGoal;
return (<>
{ isGoal ? <MadeGoal/> : <MissedGoal/> }</>
);
}createRoot(document.getElementById('root')).render(
<Goal isGoal={false} />
);Example » To learn more, see the ternary operator section.