In React, conditional rendering lets you display components based on certain conditions. This guide will explore different approaches with clear examples to help you understand how to implement conditional rendering in your applications.
if
StatementThe if
statement allows you to render different components based on a condition.
Let’s create two components to represent different outcomes:
function Success() {
return <h1>Success!</h1>;
}
function Failure() {
return <h1>Failure!</h1>;
}
Next, we’ll create a parent component that decides which component to render:
function Result(props) {
const isSuccess = props.isSuccess;
if (isSuccess) {
return <Success />;
}
return <Failure />;
}
const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(<Result isSuccess={true} />);
The if
statement checks the value of isSuccess
.
If isSuccess
is true
, the Success
component is rendered.
Otherwise, the Failure
component is rendered.
&&
OperatorThe logical &&
operator allows you to conditionally display a component or element when a condition evaluates to true
.
Let’s build a Garage
component that shows the number of cars only if there are cars in the array:
function Garage(props) {
const cars = props.cars;
return (
<div>
<h1>Garage</h1>
{cars.length > 0 && (
<h2>You have {cars.length} car(s) in your garage.</h2>
)}
</div>
);
}
const carList = ["Toyota", "Honda", "Ford"];
const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(<Garage cars={carList} />);
If cars.length > 0
evaluates to true
, the message is displayed.
If cars.length === 0
, nothing is rendered.
Try rendering an empty array:
const carList = [];
root.render(<Garage cars={carList} />);
The ternary operator provides a concise way to conditionally render elements.
condition ? renderIfTrue : renderIfFalse;
Revisiting the first example, we can use a ternary operator instead of an if
statement:
function Result(props) {
const isSuccess = props.isSuccess;
return (
<div>
{isSuccess ? <h1>Success!</h1> : <h1>Failure!</h1>}
</div>
);
}
const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(<Result isSuccess={false} />);
If isSuccess
is true
, the Success
message is rendered.
If isSuccess
is false
, the Failure
message is displayed.
Use if
statements for complex logic or when conditions require multiple steps.
Use &&
operators for conditions where no fallback component is needed.
Use ternary operators for inline conditions with two possible outcomes.
React’s conditional rendering offers multiple approaches to dynamically render components based on your application’s state or props. By mastering these techniques, you can build flexible and user-friendly interfaces.
Experiment with the examples above to see how conditional rendering can make your React applications more dynamic and responsive!
The complete source code for this project is available on GitHub