React basics 02 · Components
Children, conditions and lists
A wrapper for someone else’s content (children and slots), how to show something only sometimes and how to render a list – and why the key matters so much.
Loading lesson…
React basics 02 · Components
A wrapper for someone else’s content (children and slots), how to show something only sometimes and how to render a list – and why the key matters so much.
Loading lesson…
From lesson React basics 01 you know how to write a component, pass it props and build a page out of components. Let's use that to write a piece of an ordinary inbox: a frame with the heading "Messages", a badge with the message count and a list of messages below it.
// ❌ Only with what you know from the last lessonfunction Inbox() {return (<section className="card"> {/* a frame with a heading… */}<h3>Messages</h3><span className="badge">3</span> {/* a badge with the count… */}<ul><li>Hi, how are you?</li> {/* …and messages copied by hand */}<li>Tomorrow at 10?</li><li>Thanks!</li></ul></section>)}
At first glance it works. In a real app, though, it runs into three problems:
There's one tool for each problem, and all three are in this lesson:
// ✅ With the tools from this lesson// Card = our own component "a frame with a heading" (instead of <section> and <h3>);// we'll write it in section 1.// Message = the shape of one message: { id: number; text: string }function Inbox({ messages }: { messages: Message[] }) {return (<Card title="Messages"> {/* 1. Card supplies the frame – and everything from here… */}{messages.length > 0 && <span className="badge">{messages.length}</span>} {/* 2. the badge only when there are messages */}<ul>{messages.map((m) => <li key={m.id}>{m.text}</li>)} {/* 3. one <li> for every message in the array */}</ul></Card> {/* …down to here is the filling Card puts inside the frame */})}
And the same frame elsewhere on the page, around completely different content:
<Card title="News"><p>React 19 is out!</p> {/* this card's filling */}</Card>
Just skim that code for now – each number in the comments belongs to one of the problems above and is also the number of the section that takes it apart in detail: 1. Children and slots, 2. Conditions, 3. Lists and key. What matters is what changed:
Inbox. It's written once, in the component Card. Inbox just passes it the heading and writes its content between the tags <Card> and </Card>; Card puts it inside the frame. It wraps the news, the settings and the team the same way, and when the frame's look should change, you edit only Card. Putting components inside each other is called composition.The table shows typical wishes; what you want on the left, the tool in the middle, the section on the right:
| I want… | Tool | Section |
|---|---|---|
| a frame, window or panel that different content goes into | children and slots | 1 |
| to show something only sometimes (a badge, "Loading…", an error) | a condition | 2 |
| one of two variants (signed in / signed out) | a condition – a ternary | 2 |
| a row for every item of an array (messages, goods, tasks) | map and key | 3 |
Some recipes prepare only the wrapper and leave the filling to the guest. The baker bakes a tortilla and you say what goes in. The baker doesn't need to know every possible filling – just how to wrap the tortilla.
What for: an app has plenty of wrappers that always look the same but hold something different each time – a card frame, a pop-up window, a panel with a heading, a page layout. When: when the component should decide how the wrapper looks, but whoever uses it decides the content.
How: everything you write between the opening and closing tag of a component reaches it in the special prop children. The component only decides where to put it.
// ReactNode = the type "anything that can be rendered": JSX, text, a number, an array, or nothing.// import type = imports just a type (lesson TypeScript 01), nothing is added to the app.import type { ReactNode } from 'react'// ① THE RECIPE – a card with a heading; it gets the filling in childrenfunction Card({ title, children }: { title: string; children: ReactNode }) {return (<div className="card"><h3>{title}</h3><div className="card-body">{children}</div> {/* ← the filling goes here */}</div>)}
// ② THE ORDERS – the same card, a different filling each timefunction App() {return (<div className="row"><Card title="News"><p>React 19 is out!</p> {/* ← the first card's children */}</Card><Card title="Team"><ProfileCard name="Anna" /> {/* ← the second card's children: */}<ProfileCard name="Peter" /> {/* two cards from the last lesson */}</Card></div>)}
Card knows nothing about news or the team. It only handles the frame and the heading, so you can use it anywhere. That's the composition from the introduction: components put inside each other, each handling just its own part.
When a wrapper needs more places for content (buttons in the header, a footer), it gets more props of type ReactNode. Such places are called slots. It's nothing special in React – just an ordinary prop that gets a piece of JSX instead of text:
// ① THE RECIPE – a panel with three places for contentinterface PanelProps {title: stringactions?: ReactNode // a slot in the header (optional)footer?: ReactNode // a slot in the footer (optional)children: ReactNode // the main content}function Panel({ title, actions, footer, children }: PanelProps) {return (<section className="card"><header><strong>{title}</strong>{actions} {/* if missing, nothing is rendered */}</header><div>{children}</div>{footer !== undefined && <footer>{footer}</footer>} {/* the footer frame only with a footer */}</section>)}
// ② THE ORDER – the arrows show what goes where<Paneltitle="Tasks"actions={<button>+ Add</button>} // → {actions} in the headerfooter={<small>3 tasks</small>} // → {footer} in the footer><ul> {/* → {children} in the middle */}<li>Shopping</li><li>Cleaning</li><li>Paying the rent</li></ul></Panel>
Why a condition for the footer but not for the actions slot? React doesn't render a missing slot (undefined), so {actions} without buttons simply shows nothing. But the footer has its own <footer> tag around it, and without the condition it would appear empty. How conditions work is in the very next section.
| Kind of prop | Who decides the look | Example |
|---|---|---|
| a data prop (text, a number…) | the component – it builds the JSX from the detail itself | title="Tasks" |
| a slot / children (ReactNode) | whoever uses the component – they send finished JSX | actions={<button>…</button>} |
The table sums up the difference: the component processes a data prop, but just puts a slot in its prepared place.
What you see: Two cards rendered by the same component ProfileCard. The first got all the props plus content between the tags (children). The second got only name.
Try it:
children – the component just put it in its prepared place.{children !== undefined && …}. Thanks to it, the second card, which has no filling, doesn't render even an empty wrapper.The takeaway: One recipe, different orders. Props change the details, children supplies a whole piece of content, and the component doesn't need to know what's in it.
Loading the interactive part…
Recipes often contain conditions: "if the guest is vegetarian, leave out the ham". What it's for on a page: a badge with the message count only when there are some, "Loading…" until the data arrives, a different button for a signed-in and a signed-out user.
React has no special syntax for it. Conditions are written in ordinary JavaScript from lesson JavaScript 06; you just pick one of four forms depending on the situation. All four are in one example – an inbox icon:
// user is either an object with a name, or null (nobody is signed in) – a union from lesson TypeScript 02function Inbox({ user, count }: { user: { name: string } | null; count: number }) {// 1) EARLY RETURN – when nobody is signed in, the rest of the recipe doesn't matter.// The function ends right here and returns just a request to sign in.if (user === null) return <p>Please sign in.</p>return (<div>{/* 2) && – either something or nothing: the badge only when there are messages */}{count > 0 && <span className="badge">{count}</span>}{/* 3) A TERNARY – one of two variants */}<p>{count > 0 ? 'You have new messages' : 'Nothing new'}</p></div>)}
With count > 0 && <span>…</span> it helps to know exactly what && does: when the left side is truthy, the result is the right side (the badge); when it's falsy, the result is the left side – false. And React renders neither false, null nor undefined, so there's nothing on the page.
The fourth form suits more variants: instead of a chain of ternaries you prepare an object and look the variant up in it by the value.
// 4) AN OBJECT OF VARIANTS// status is one of three strings – a union from lesson TypeScript 02function SaveStatus({ status }: { status: 'loading' | 'error' | 'done' }) {// object key = a possible value of status, value = the JSX shown for itconst variants = {loading: <p>Loading…</p>,error: <p className="bad">Something went wrong</p>,done: <p className="ok">Done</p>,}return variants[status] // square brackets = the property named by a variable's value (lesson JavaScript 03)}// use: <SaveStatus status="error" /> → shows "Something went wrong"
When to use which form – the form on the left, the situation it suits on the right:
| Form | When to use it |
|---|---|
if (…) return … | The component has nothing to show: nobody is signed in, data is loading, an error happened. The most readable. |
condition && <X /> | Either something or nothing. The condition must be true/false – see the zero trap below. |
condition ? <A /> : <B /> | Two variants in the same place. |
variants[value] | Three or more variants based on one value. |
Why "must be true/false"? Let's write the shorter count && … instead of count > 0 && …:
{count && <span className="badge">{count}</span>} // ❌
count is 3, the left side is truthy → the result is the right side, the badge. Fine.count is 0, the left side is falsy → the result is the left side, that is the number 0.false, but it does render numbers. A lonely "0" appears on the page.The fix: always put a real true/false into the condition – count > 0, items.length > 0, user !== null.
What you see: At the top, three lines showing the message count in three forms: wrong (count &&), right (count > 0 &&) and with a ternary. At the bottom, a user badge written with an early return.
Try it:
count is 0. In the "Wrong" line you'll see a lonely 0; the "Right" line is empty.UserBadge ends on its first line and doesn't deal with the rest at all.The takeaway: Only true/false goes into &&. For two variants use a ternary, for "render nothing / loading / error" an early return.
Loading the interactive part…
What for: almost every app shows a list – tasks, messages, goods, comments. The data comes as an array and every item should become a piece of the page. How: with the ordinary map method from lesson JavaScript 04 – you turn an array of data into an array of JSX. React can render an array of JSX one item after another.
// The data – an array of tasks. Each has an id that never changes.const tasks = [{ id: 17, label: 'Shopping' },{ id: 42, label: 'Cleaning' },]// ① THE RECIPE – one row of the listfunction TaskRow({ task }: { task: { id: number; label: string } }) {return <li>{task.label}</li>}// ② THE LIST – map turns every task into one <TaskRow>function TaskList() {return (<ul>{tasks.map((task) => (<TaskRow key={task.id} task={task} /> // key = the item's "name", see below))}</ul>)}// map returns an array: [<TaskRow key={17} … />, <TaskRow key={42} … />]
What in the example is fixed and what did you name yourself? Only two words are fixed – key and map. The table shows every word from the example; the middle column says who decides the name:
| Word | Who decides it | What it means |
|---|---|---|
key | React – it must be called exactly that | the item’s name, which React recognises it by; React keeps it for itself and doesn’t pass it to the component |
map | JavaScript – an array method | turns each item of the array into one element |
tasks | you | the array with the data – todos or items is fine too |
task | you | one item, the one map is working on right now (the function’s parameter) |
id, label | you (or the database) | the item’s properties; id suits the key because it differs for every item |
TaskRow | you | the component for one row – it just has to start with a capital letter |
task={task} | you | an ordinary prop: its name on the left, the variable you send into it on the right |
Want to show only some items? Pick them with filter first (also lesson JavaScript 04), and only then map: tasks.filter((t) => !t.done).map((t) => <TaskRow key={t.id} task={t} />).
A teacher brings the class's marked notebooks back. There are no names on them, so they go out desk by desk: the first notebook to the first desk, the second to the second… As long as everyone sits where they did last time, it works. But today a new pupil came and sat at the first desk. The notebooks go out the same way – the new pupil gets Emma's, Emma gets Jack's, and so on. Nobody miscounted, and still everyone holds someone else's notebook. Just write a name on each notebook: then the teacher gives everyone their own, wherever they sit, and the new pupil gets a new, empty one.
React does the same as the teacher every time a list changes. The list's rows are the pupils, and each row can have its own "notebook" – content that doesn't come from the data, say half-typed text in a field. When a list changes, React has to recognise which row is which: which is new, which disappeared and which just moved – and give each one its own content back. key is the name on the notebook: React recognises rows by it. Without a key (or with the position as the key) it hands things out by order – like the teacher by desk.
key goes on the element that map returns (here <TaskRow>), not inside the component.The function you give to map gets, besides the item, a second parameter too – the item's position in the array (the index: 0, 1, 2…). It's tempting to use it as the key. Let's try both options on a class – a list of pupils where every row has a "notebook" field you can type into:
// Data – the pupils of a class. Each one has an id that never changes.const pupils = [{ id: 17, name: 'Emma' },{ id: 42, name: 'Jack' },]// A pupil's row: the name and a "notebook" field. The row remembers the text in the field itself – it isn't in the data.function PupilRow({ pupil }: { pupil: { id: number; name: string } }) {return (<li>{pupil.name} <input aria-label="Notebook" /></li>)}// ❌ A key by position: the second parameter of the function in map is the position (you pick the name index yourself)pupils.map((pupil, index) => <PupilRow key={index} pupil={pupil} />)// Emma gets key 0, Jack key 1 – but only until someone sits down in front of them// ✅ A key from the data: the id belongs to the pupil wherever they are in the arraypupils.map((pupil) => <PupilRow key={pupil.id} pupil={pupil} />)// Emma has key 17, Jack key 42 – always
key={index} is exactly the teacher handing out by desk. You write "A in the spelling test" into Emma's notebook, and then a new pupil, Tom, sits down at the first desk – at the start of the list. The table shows how React pairs the rows by key; the last column shows who gets Emma's notebook:
| Key | Before Tom arrives | After Tom arrives | Who has the "A in the spelling test" notebook |
|---|---|---|---|
key={index} | 0 = Emma, 1 = Jack | 0 = Tom, 1 = Emma, 2 = Jack | Tom (row 0 kept its content) |
key={pupil.id} | 17 = Emma, 42 = Jack | 99 = Tom, 17 = Emma, 42 = Jack | Emma (row 17 just moved) |
With the index, React thinks row 0 is still the same row that just has a different name next to it now – and leaves it Emma's notebook. So Tom holds someone else's notebook and Emma holds Jack's, just like with the teacher. With the id, it knows row 99 is new (it gets an empty notebook) and just moves rows 17 and 42 together with their notebooks.
What you see: The same class rendered twice. On the left with key={index}, on the right with key={pupil.id}. Every pupil has their own "notebook" field. The button seats a new pupil at the first desk in both lists.
Try it:
The takeaway: A row's content belongs to its key. A key by position hands it to the wrong row once the order changes – like the teacher handing out by desk. A stable id works like the name on the notebook.
Loading the interactive part…
| Key | When |
|---|---|
key={item.id} | ✅ always when the items have an id – which is almost always |
key={index} | ⚠️ only for a list that is never reordered or filtered, never gets items added in the middle or at the start, and whose rows have no content of their own (say links in a footer) – handing out by desk only works while nobody changes seats |
key={Math.random()} | ❌ never – a new name on every render: every pupil would get a new, empty notebook each time (React would throw all rows away and make them again) |
The table sums up which key to use when. When the data has no id, create one when the item comes into being (when it's added), say with the browser function crypto.randomUUID(), which returns a random unique text, and store it with the item. Never during render.
The component template from lesson React basics 01 with everything from this lesson added. You'll find the same pattern in the Cheat sheets on the React tab.
// the file src/components/ProductList.tsximport type { ReactNode } from 'react'// 1. THE SHAPE OF THE DATA – one item of the list; id never changes, so it serves as the keyinterface Product {id: numbername: stringprice: numbersale: boolean}// 2. A WRAPPER WITH A FILLING AND A CONDITION – one cardinterface ProductCardProps {name: stringprice: numbersale?: boolean // an optional prop – when nobody passes it, it's undefinedchildren?: ReactNode // optional content between the tags (section 1)}// sale = false → a default value (React basics 01): without the sale attribute, sale is false, not undefinedexport function ProductCard({ name, price, sale = false, children }: ProductCardProps) {return (<div className="card"><strong>{name}</strong>{sale && <span className="badge">Sale</span>} {/* section 2: only true/false in && */}<div>${price}</div>{children} {/* the filling from the parent; if missing, nothing */}</div>)}// 3. A LIST FROM AN ARRAY – a card for every productexport function ProductList({ products }: { products: Product[] }) {// section 2: an early return – an empty array = nothing to showif (products.length === 0) return <p>Nothing here.</p>return (<div className="row">{/* section 3: one card from every product; key from a stable id */}{products.map((p) => (<ProductCard key={p.id} name={p.name} price={p.price} sale={p.sale} />))}</div>)}// use in a parent (products = an array of products, say from a server):// <ProductList products={products} />// a card with a filling: <ProductCard name="Apple" price={1}><small>Local</small></ProductCard>
The table is an index; what you want on the left, the code in the middle, the section with the explanation on the right:
| I want… | Code | Section |
|---|---|---|
| a wrapper for someone else’s content | { children }: { children: ReactNode } | 1 |
| another place for content (buttons, a footer) | actions?: ReactNode | 1 |
| to show something only when a condition holds | {count > 0 && <Badge />} | 2 |
| one of two variants | {done ? <A /> : <B />} | 2 |
| to show nothing (loading, nobody signed in) | if (!user) return <p>…</p> | 2 |
| three or more variants | variants[status] | 2 |
| a list from an array | {items.map((i) => <Row key={i.id} item={i} />)} | 3 |
| only some items | items.filter(…).map(…) | 3 |
&& (count > 0, not count).key from a stable id – on the element map returns.A list from an array and one condition. Both have their shape ready in the code; you fill in just two places.
Task is in the comments in the code below – at the top of the file and at the places marked TODO.
row, stack, card, list, btn, input or muted are the course's ready-made styles in src/styles.css (row = side by side, stack = stacked, card = bordered box, muted = grey text).Loading the interactive part…
The first challenge practises sections 1 and 2 – you'll write a "tortilla", a wrapper that knows nothing about its content. The second practises sections 2 and 3: conditions, a list and keys. You'll find the template in section 4.
A panel with a title that accepts any filling through children and optional places for buttons and a footer. You'll see this pattern in every component library. What should show at the end is in the comments in the code.
Task is in the comments in the code below – at the top of the file and at the places marked TODO.
row, stack, card, list, btn, input or muted are the course's ready-made styles in src/styles.css (row = side by side, stack = stacked, card = bordered box, muted = grey text).Loading the interactive part…
Render a list of products with prices, highlight the sold-out ones and, depending on the onlyInStock prop, show either all of them or only the ones in stock. What should show is in the comments in the code.
Task is in the comments in the code below – at the top of the file and at the places marked TODO.
Loading the interactive part…
ReactNode) let a component wrap content it knows nothing about – a frame is written once and used around anything.&&, a ternary or an object of variants – and only true/false in &&, otherwise a 0 gets rendered.products, Product)products, Product – from the file src/course/fakeApi.en.ts. The course fake API: data and functions pretending to be a server (with a delay, sometimes even with an error). In a real app you would call fetch() here.export interface Product {id: numbername: stringcategory: 'fruit' | 'vegetables' | 'bakery' | 'dairy'price: numberinStock: boolean}export const products: Product[] = [{ id: 1, name: 'Apple', category: 'fruit', price: 12, inStock: true },{ id: 2, name: 'Banana', category: 'fruit', price: 8, inStock: true },{ id: 3, name: 'Pear', category: 'fruit', price: 15, inStock: false },{ id: 4, name: 'Carrot', category: 'vegetables', price: 6, inStock: true },{ id: 5, name: 'Tomato', category: 'vegetables', price: 9, inStock: true },{ id: 6, name: 'Cucumber', category: 'vegetables', price: 19, inStock: false },{ id: 7, name: 'Bread roll', category: 'bakery', price: 3, inStock: true },{ id: 8, name: 'Bread', category: 'bakery', price: 45, inStock: true },{ id: 9, name: 'Milk', category: 'dairy', price: 22, inStock: true },{ id: 10, name: 'Cheddar', category: 'dairy', price: 39, inStock: true },{ id: 11, name: 'Yogurt', category: 'dairy', price: 14, inStock: false },{ id: 12, name: 'Orange', category: 'fruit', price: 11, inStock: true },]
row, stack, card, list, btn, input or muted are the course's ready-made styles in src/styles.css (row = side by side, stack = stacked, card = bordered box, muted = grey text).