Conditional Rendering
if&&and?:operators can be used to render JSX conditionally.
Starter Code
function Item({ name, isPacked }) {
return <li className="item">{name}</li>;
}
export default function PackingList() {
return (
<section>
<h1>Sally Ride's Packing List</h1>
<ul>
<Item isPacked={true} name="Space suit" />
<Item isPacked={true} name="Helmet with a golden leaf" />
<Item isPacked={false} name="Photo of Tam" />
</ul>
</section>
);
}
Conditionally render Item
- ✅ item if its isPacked prop is
true
function Item({ name, isPacked }) {
if (isPacked) {
return <li className="item">{name} ✅</li>;
}
return <li className="item">{name}</li>;
}
- returning nothing with
null
function Item({ name, isPacked }) {
if (isPacked) {
return null;
}
return <li className="item">{name}</li>;
}
Warning
Returning null is rare and not recommended as the result of using null may surprise developers
With logical && operator
function Item({ name, isPacked }) {
return (
<li className="item">
{name} {isPacked && "✅"}
</li>
);
}
Warning
- The LHS of
&&cannot be a number 0 && <p>New Messages</p>is not a uplifting expression cuzReactwould just render0.- You need to ensure that the RHS is a boolean expression.