Conditional Rendering
Your App components will eventually need to display differently depending on a condition. In React, there is no special syntax for writing conditions. Instead, you rely on the same techniques you use when writing JavaScript code.
As such, you will use standard JavaScript operators like if/else, the ? conditional operator or the logical && syntax to conditionally include JSX to represent the current state of the component that needs to be rendered.
If/Else
let content;
if (isLoggedIn) {
content = <DashboardPanel />;
} else {
content = <LoginForm />;
}
return (
<div>{content}</div>
);
Conditional Operator ?
Unlike if, this works inside JSX and can lead to more compact code
return (
<div>
{isLoggedIn ? (
<DashboardPanel />
) : (
<LoginForm />
)}
</div>
);
Logical AND Operator &&
Useful if there’s no need for the else branch.
return (
<div>
{isLoggedIn && <DashboardPanel />}
</div>
);
⚠️ Pitfall: Don’t put a number on the left side of
&&. If the left side is0, the whole expression evaluates to0, and React will render the0itself rather than nothing. For example,messageCount && <p>New messages</p>renders0when there are no messages. To fix it, make the left side a boolean:messageCount > 0 && <p>New messages</p>. See Conditional Rendering on react.dev.
Rendering nothing
If you need a given React component to render nothing, simply return null. This prevents the component from rendering.
function Banner(props) {
if (!props.message) {
return null;
}
return (
<div>{props.message}</div>
)
}