Conditional Contents
Conditional content means showing, hiding or swapping parts of a component based on state or props, typically after rendering a list. Common cases are showing a "No items found" message when a filtered list is empty, displaying a loading indicator while data arrives, or revealing extra details when a user clicks. In React you handle this with JavaScript expressions inside JSX or with logic placed before the return.
Handling the empty list
After learning to render lists with map and keys, the next practical need is what to show when the array has nothing in it. Without a check, the user just sees a blank area and cannot tell whether the app is broken.
function ExpenseList({ items, year }) {
const filtered = items.filter((e) => e.date.getFullYear() === year);
let content = <p className="empty">No expenses found for this year.</p>;
if (filtered.length > 0) {
content = (
<ul>
{filtered.map((e) => (
<li key={e.id}>
{e.title}: Rs {e.amount}
</li>
))}
</ul>
);
}
return (
<section>
<h2>Expenses</h2>
{content}
</section>
);
}
Storing the JSX in a variable keeps the return statement short and readable, especially when each branch is several lines long.
Loading, error and data states together
When a component fetches data, it usually has three states. A small set of early returns handles them clearly.
function UserList() {
const [users, setUsers] = useState([]);
const [status, setStatus] = useState('loading'); // 'loading' | 'error' | 'done'
useEffect(() => {
fetch('/api/users')
.then((r) => (r.ok ? r.json() : Promise.reject(r.status)))
.then((data) => { setUsers(data); setStatus('done'); })
.catch(() => setStatus('error'));
}, []);
if (status === 'loading') return <p>Loading users...</p>;
if (status === 'error') return <p role="alert">Could not load users.</p>;
if (users.length === 0) return <p>No users yet.</p>;
return (
<ul>
{users.map((u) => <li key={u.id}>{u.name}</li>)}
</ul>
);
}
Keeping one status value instead of separate isLoading and hasError booleans avoids impossible combinations, such as loading and error both being true.
Toggling details with state
For content the user reveals, keep a boolean in state and render the extra part with &&: {showDetails && <Details />}. A button flips it with setShowDetails((s) => !s). Using the updater function form ensures you flip the latest value even if several updates are batched together.
Hiding with CSS versus not rendering
Not rendering an element removes it from the DOM, and any state inside it is lost. If a user types into a form inside a panel and you hide the panel conditionally, their text disappears when it is shown again. When state should survive, keep the element mounted and hide it with a class or the hidden attribute instead. When it should reset, conditional rendering is exactly right.
A common bug: rendering a number
Writing {filtered.length && <ul>...</ul>} prints 0 when the list is empty, because React renders the number zero. Compare explicitly with filtered.length > 0. Also remember that every conditional branch that renders a list still needs a stable key on each item.
Watch where the conditions live, too. If the same check, such as filtered.length > 0, appears in several places, compute it once as a named variable like hasResults. The JSX then reads almost like a sentence, and changing the rule later means editing a single line.
In practice
- Always design the empty, loading and error views, not just the happy path.
- Use a variable or early returns when branches are long.
- Choose between unmounting and CSS hiding based on whether state should persist.
- Keep the left side of
&&a true boolean.
Ready to master real-world web development?
Learn HTML, CSS3, Bootstrap and JavaScript hands-on with mentor-led sessions.