Conditional Rendering β Rendering Different UIs Based on Conditions
After completing this topic, you will:
Know several patterns for displaying different components based on conditions in React.
Why is it necessary?
You need to display different screens based on whether a user is logged in. You need to display a spinner while data is loading and an error message if there is an error. This is rendering different UIs based on conditions, which is called conditional rendering.
Pattern 1: Early Return
function Dashboard({ user }) {
if (!user) {
return <LoginForm />;
}
return <UserDashboard user={user} />;
}Check the condition at the beginning of the function and return immediately. This is the most readable pattern. You don't have to put complex conditions inside JSX.
Pattern 2: Ternary Operator
function Greeting({ isLoggedIn }) {
return (
<div>
{isLoggedIn ? <UserMenu /> : <LoginButton />}
</div>
);
}Use the ternary operator when writing conditions inside JSX. It is suitable when you need to display one of two things.
It becomes difficult to read when nested:
// Bad example
{isLoading ? <Spinner /> : error ? <Error /> : <Content />}In this case, use early return or separate it into a separate function.
Pattern 3: && Operator
function Notification({ count }) {
return (
<div>
{count > 0 && <Badge count={count} />}
</div>
);
}Use it when you need to show or not show something. If the else part of the ternary operator is null, you can use &&.
Caution: The number 0 is falsy, but React renders it.
// Caution: If count is 0, "0" will be displayed on the screen
{count && <Badge />}
// Safe way
{count > 0 && <Badge />}Pattern 4: Storing in a Variable
function StatusMessage({ status }) {
let message;
if (status === "loading") message = <Spinner />;
else if (status === "error") message = <ErrorBanner />;
else if (status === "empty") message = <EmptyState />;
else message = <DataTable />;
return <div className="container">{message}</div>;
}If there are three or more branches, it is cleaner to store it in a variable.
Returning null
function MaybeTooltip({ show, text }) {
if (!show) return null;
return <div className="tooltip">{text}</div>;
}Returning null renders nothing. Use it when you want to hide the component itself.
It is different from display: none in CSS. null completely disappears from the DOM, while display: none remains in the DOM but is not visible.
Key takeaways
Early return is the most readable conditional rendering pattern. Use the ternary operator to display one of two things, and && to show or not show something. If there are many branches, store it in a variable or separate the component.