Conditional Rendering
Show different UI depending on the data — logged in vs out, loading vs loaded, empty vs full.
What you will learn
- Render conditionally with the ternary operator
- Use && for show/hide
- Handle empty states
The ternary in JSX
Inside { }, use the ternary condition ? a : b to choose between two pieces of UI.
function App() {
const isLoggedIn = true;
return (
<div>
{isLoggedIn
? <h3>Welcome back! 👋</h3>
: <h3>Please log in.</h3>}
</div>
);
}The ternary reads as a question: isLoggedIn ? A : B means “if isLoggedIn is true, show A, otherwise show B”. Here isLoggedIn is true, so React shows the “Welcome back” heading. Flip it to false and the “Please log in” heading appears instead. It is a one-line if/else you can use right inside { }.
Note: Output:
Welcome back! 👋
(If isLoggedIn were false, it would instead read Please log in.)
Show/hide with &&
Use condition && <Element/> to show something only when the condition is true.
function App() {
const cart = ["Book", "Pen"];
return (
<div>
<p>You have {cart.length} items.</p>
{cart.length === 0 && <p>Your cart is empty.</p>}
{cart.length > 0 && <p>Ready to checkout! ✅</p>}
</div>
);
}When you only want to show something or nothing (not an either/or), use &&. condition && <Element/> means “if the condition is true, show the element; if false, show nothing”. The cart here has 2 items, so cart.length === 0 is false (the empty message is hidden) and cart.length > 0 is true (the checkout message appears).
Note: Output: You have 2 items. Ready to checkout! ✅ The “Your cart is empty” line is skipped because the cart is not empty.
Tip: Common real use: show a “Loading…” message while data is being fetched, then the data once it arrives. You will do exactly this in the data-fetching lesson.
Q. Which is used in JSX to render one of two elements based on a condition?
✍️ Practice
- Show “Adult” or “Minor” based on an
agevariable using a ternary. - Show a “No items” message only when a list is empty using
&&.
🏠 Homework
- Build a component that shows a login/logout button depending on an
isLoggedInvalue.