Chapter 4 · Describing the UI

Conditions & Lists

Show different things depending on your data, and turn arrays of data into lists of components.

You will learn
  • Four ways to render something only sometimes: if, null, ? : and &&
  • How to render an array with map() and filter it with filter()
  • What key is and why React needs it

Part A · Conditional rendering

Components often need to show different things in different situations. In React there's no special syntax for this: you use ordinary JavaScript, like if, && and ? :.

1. if with an early return

2. Return null to show nothing

A component can return null to render nothing. It's often clearer to make the decision in the parent, though, as in the next two patterns.

3. The ternary ? : for "this or that"

Read it as: "if isPacked, then show name + ' ✅', otherwise show name." Because it's an expression, it can go inside braces in JSX, and it can hold JSX too:

4. Logical AND && for "this or nothing"

Read it as: "if isPacked, then show ✅, otherwise nothing." React renders nothing for false, null, undefined and true.

Don't put numbers on the left of && 0 && anything evaluates to 0, and React does render the number 0.

5. Assigning JSX to a variable (most flexible)

When the conditions get complicated, this style is the easiest to read. JSX is just a value, so you can store it in a variable like any other.

Want…Use
Completely different outputif (...) return ...
Nothing at allreturn null
A or B, inline{cond ? <A /> : <B />}
A or nothing, inline{cond && <A />}
Complex logicBuild a variable with let and if, then render it

Part B · Rendering lists

Most apps show lists: products, messages, users. You keep the data in an array and use JavaScript's map() to turn each item into JSX.

From array to list with map()

map() creates a new array by running a function on every item. Here the function turns each string into an <li>. React can render an array of JSX directly. This works, but the console shows a warning: "Each child in a list should have a unique 'key' prop." We'll fix that shortly.

Arrays of objects

Real data is usually an array of objects:

Filtering with filter()

To show only the chemists, first filter the array, then map it:

Arrow functions and return

Keys: helping React keep track

A key is a unique name for each item in a list. It lets React tell the items apart, even when they're added, removed or reordered.

Think of files on your desktop. If they only had positions ("the 3rd file") and you deleted one, every file after it would be "renamed". Names (keys) let React know that "this is still the same item, it just moved." Without good keys, React can mix up items, for example keeping text typed into the wrong row.

Rules of keys

Avoid using the array index as the key people.map((person, index) => <li key={index}>...) stops the warning, but if items are inserted, removed or reordered, the indexes shift and bugs appear. It's OK only for lists that never change.
Keys aren't props React uses key itself, and your component doesn't receive it. If the component needs the ID, pass it separately: <Profile key={id} userId={id} />.

Several elements per item

The short <> fragment can't take a key. Use the long form, <Fragment>:

More examples

Example 1: loading, error and data states

A very common pattern: show different UI depending on where a request is.

Example 2: choosing a component from an object (instead of many ifs)

Example 3: nested lists

Each map needs its own keys. They only have to be unique within their own list.

Example 4: an empty state

Example 5: sorting before rendering

Here the index is used for display (the trophy), while the key still uses the stable id.

Recap

  • Conditional rendering is plain JavaScript: if, ? :, &&, or null.
  • Keep a number from appearing by making the left side of && a true/false value.
  • Render lists with array.map(), and narrow them down with array.filter().
  • Every list item needs a unique, stable key, ideally an ID from your data.

Exercises

1. Show an icon for packed items

Render ❌ for unpacked items and ✅ for packed ones, using the ternary operator.

Show solution

2. Two lists from one array

Using the people array above, render two lists: Chemists and Everyone else.

Show solution

3. A todo list from data

Turn this array into a <ul>. Strike through the done items with <del>, and show "All done! 🎉" if every item is done. Hint: todos.every(t => t.done).

Show solution

4. Time-based greeting 🟢 easy

Show "Good morning" before 12:00, "Good afternoon" before 18:00, and "Good evening" otherwise. Hint: new Date().getHours().

Show solution

5. Logged in or not 🟢 easy

Create <Nav isLoggedIn={...} userName="Asha" />. If logged in, show "Welcome back, Asha" and a Logout button. If not, show a Sign in button only.

Show solution

6. Numbered movie list 🟢 easy

Render [{ id: 'm1', title: 'Inception' }, { id: 'm2', title: 'Interstellar' }, ...] as "#1 Inception", "#2 Interstellar"… using the index for the number, but the id as the key.

Show solution

7. Cheap products 🟢 easy

From a products array ({ id, name, price }), show only those under ₹500. If none match, show "Nothing under ₹500".

Show solution

8. Fix the key problems 🟡 medium

Show solution

1) Math.random() gives a new key on every render, so React re-creates every row and loses its state. Use key={user.id}. 2) The key must be on the outermost element returned from map, here the <div>.

9. Recipes with ingredients 🟡 medium

Render each recipe as an <h2>, followed by a <ul> of its ingredients.

Show solution

The ingredient names are unique within each recipe, so they work as keys.

10. Group by profession 🔴 hard

Using the people array from this chapter, render one section per profession (mathematician, chemist, physicist…), each with its list of people. Don't hard-code the profession names: work them out from the data.

Show solution

new Set(...) removes duplicates, and [...set] turns it back into an array.