React course menu
Conditional Rendering in React: if, Ternary and &&
Show different content based on conditions in React: if statements with early returns, the ternary operator, logical && for optional content, the 0 pitfall, returning null, and choosing elements with variables and objects.
On this page
Components often need to show different things depending on data: a "Log in" or "Log out" button, an empty-cart message, a sale badge. JSX has no if syntax of its own, so you use ordinary JavaScript.
if with an early return#
For completely different output, use if before the return:
function Inbox({ messages }) {
if (messages.length === 0) {
return <p>No new messages. 🎉</p>;
}
return <p>You have {messages.length} new messages.</p>;
}
export default function App() {
return (
<div>
<Inbox messages={[]} />
<Inbox messages={["Hi", "Meeting at 5"]} />
</div>
);
}The ternary operator inside JSX#
condition ? a : b is an expression, so it works inside { }. Use it to choose between two options:
function StockLabel({ quantity }) {
return (
<p>
{quantity > 0 ? <span style={{ color: "green" }}>In stock ({quantity})</span> : <span style={{ color: "crimson" }}>Out of stock</span>}
</p>
);
}
export default function App() {
return (
<div>
<StockLabel quantity={12} />
<StockLabel quantity={0} />
</div>
);
}&& for "show or nothing"#
condition && <Element /> shows the element when the condition is true and nothing when it is false:
function Product({ name, onSale }) {
return (
<p>
{name} {onSale && <strong style={{ color: "white", background: "crimson", padding: "0 6px" }}>SALE</strong>}
</p>
);
}
export default function App() {
return (
<div>
<Product name="Running shoes" onSale />
<Product name="Socks" onSale={false} />
</div>
);
}React renders nothing for false, null, undefined and true.
The 0 pitfall#
React does render the number 0. So count && <Badge /> shows a stray "0" when count is 0:
export default function App() {
const unread = 0;
return (
<div>
<p>Wrong: {unread && <span>{unread} unread</span>}</p>
<p>Right: {unread > 0 && <span>{unread} unread</span>}</p>
</div>
);
}Make the left side a real true/false value: count > 0 &&, or use a ternary.
Returning null#
A component can return null to render nothing at all:
function Warning({ show, children }) {
if (!show) return null;
return <p style={{ background: "#fff3bf", padding: 8 }}>⚠️ {children}</p>;
}
export default function App() {
return (
<div>
<Warning show={true}>Your session expires in 5 minutes.</Warning>
<Warning show={false}>You will not see this.</Warning>
<p>Page content</p>
</div>
);
}Choosing with a variable or a lookup object#
When there are more than two cases, compute the content first, or map values to elements with an object:
const STATUS = {
placed: { text: "Order placed", color: "#1c7ed6" },
shipped: { text: "On the way", color: "#f08c00" },
delivered: { text: "Delivered", color: "#2f9e44" },
};
function OrderStatus({ status }) {
const info = STATUS[status] ?? { text: "Unknown status", color: "gray" };
return <p style={{ color: info.color }}>● {info.text}</p>;
}
export default function App() {
return (
<div>
<OrderStatus status="placed" />
<OrderStatus status="shipped" />
<OrderStatus status="delivered" />
<OrderStatus status="lost" />
</div>
);
}Common mistakes#
Practice#
Practice exercise
Write a Greeting component that takes user (an object with name, or null). If there is no user, show a "Log in" button; otherwise show "Welcome back, NAME" and, if user.isAdmin is true, an "Admin" label after it.
Show hint
Return early when !user. For the label, use user.isAdmin && <span>...</span>.
Show solution
function Greeting({ user }) {
if (!user) return <button>Log in</button>;
return (
<p>
Welcome back, {user.name} {user.isAdmin && <span>(Admin)</span>}
</p>
);
}
export default function App() {
return (
<div>
<Greeting user={null} />
<Greeting user={{ name: "Kiran" }} />
<Greeting user={{ name: "Anita", isAdmin: true }} />
</div>
);
}Key takeaway#
Next: Rendering Lists and Keys.
Finished this lesson?