Sub topic 9
Conditional rendering with if and early return
This chapter assumes you know JavaScript arrays and if statements, can write React function components with props and JSX, and have used useState. It covers the most basic way to decide what a component shows: plain if statements and early returns.
Components are just functions
A React component is a function that returns a description of the UI. Because it is a normal function, you can use any JavaScript control flow before the return. JSX itself cannot contain an if statement, since JSX accepts only expressions. The usual fix is to put the if above the JSX, in the function body.
Early return
An early return exits the function as soon as you know what to show. The rest of the component then runs only when the early condition is false.
function Cart({ items }) {
if (items.length === 0) {
return <p>Your cart is empty.</p>;
}
return (
<ul>
{items.map(item => (
<li key={item.id}>{item.name}</li>
))}
</ul>
);
}When items is empty, React gets the paragraph and never reaches the list. When items has entries, the if is skipped and the list renders.
This style has two benefits:
- The special case is handled first, so the main output below it needs no extra nesting.
- Later code can assume the special case is already ruled out.
How the decision flows
Several guards in a row
You can stack early returns. Components that load data often check for a loading state, then an error, then the real content.
function Orders({ orders, isLoading, error }) {
if (isLoading) {
return <p>Loading...</p>;
}
if (error) {
return <p>Something went wrong: {error.message}</p>;
}
return (
<ul>
{orders.map(order => (
<li key={order.id}>{order.title}</li>
))}
</ul>
);
}Order matters. Here the loading check comes first, so the error and the list are never touched while data is still loading.
Assigning JSX to a variable
Sometimes only part of the output changes. You can store JSX in a variable with let and if, then place it in the final return.
function Greeting({ user }) {
let content;
if (user) {
content = <p>Welcome back, {user.name}.</p>;
} else {
content = <p>Please sign in.</p>;
}
return <section>{content}</section>;
}Use this form when the surrounding markup stays the same and only the inner part varies. Use an early return when the whole output differs.
Common mistakes
- Returning nothing by accident. A component that reaches the end without a
returngivesundefined. In current React versions, this renders nothing without error. If you meant to render nothing, returnnullexplicitly so your intent is clear. - Calling hooks after an early return. Hooks such as
useStatemust run in the same order on every render. Put every hook call above any early return, or React will report a hooks-order error when the condition changes. - Putting
ifinside JSX braces.{if (x) ...}is a syntax error. Use anifabove thereturn, or switch to a ternary or&&, which the next chapters cover.
import { useState } from 'react';
function Panel({ items }) {
// Correct: the hook runs before any early return.
const [open, setOpen] = useState(true);
if (items.length === 0) {
return null;
}
return (
<div>
<button onClick={() => setOpen(!open)}>Toggle</button>
{open && <p>{items.length} items</p>}
</div>
);
}Exercise
Exercise
A component calls useState after an if (!user) { return null; } line. It works on the first render, then React reports an error after user changes. What is wrong, and how do you fix it?
Show answer
On the first render the early return skips the useState call, so a later render that gets past the early return calls a different number of hooks. React requires hooks to run in the same order every render. Move the useState call above the early return.
Exercise
Rewrite this so the empty case uses an early return: function Tags({ tags }) { return tags.length ? <ul>{tags.map(t => <li key={t}>{t}</li>)}</ul> : <p>No tags.</p>; }
Show answer
function Tags({ tags }) { if (tags.length === 0) { return <p>No tags.</p>; } return <ul>{tags.map(t => <li key={t}>{t}</li>)}</ul>; }