Apr 23, 2025
React allows components to conditionally render JSX based on certain conditions using JavaScript syntax such as if statements, &&, and the ?: ternary operator. This enables dynamic rendering of components based on the given conditions.
PackingList with Item components that may be marked as packed.
isPacked is true.if/else statements to return different JSX trees.function Item({ name, isPacked }) {
if (isPacked) {
return <li className="item">{name} </li>;
}
return <li className="item">{name}</li>;
}
nullnull to prevent rendering.if (isPacked) {
return null;
}
return <li className="item">{name}</li>;
?:):return (
<li className="item">{isPacked ? name + ' ' : name}</li>
);
&&): Conditional rendering if true, otherwise render nothing.return (
<li className="item">{name} {isPacked && ''}</li>
);
? :)<del> if the item is packed.function Item({ name, isPacked }) {
return (
<li className="item">
{isPacked ? (
<del>
{name + ' '}
</del>
) : (
name
)}
</li>
);
}
&&)let to assign and reassign JSX based on conditions.let itemContent = name;
if (isPacked) {
itemContent = name + " ";
}
return (
<li className="item">{itemContent}</li>
);
if, save JSX to a variable, and use conditional operators for flexibility.{cond ? <A /> : <B />} and {cond && <A />} for conditional rendering.?: when isPacked is not true.function Item({ name, isPacked }) {
return (
<li className="item">
{name} {isPacked ? '' : '?'}
</li>
);
}