Today: rendering lists
Real pages show lists: tasks, messages, search results. The data usually
arrives as an array of objects, and you turn each object into some JSX. In
JavaScript, "turn every item into something else" is the array's map method.
map: one element per item
npm install and npm run dev. topics.map(...) calls the arrow function once per topic and collects the
results into a new array of <li> elements. React shows an array of elements
one after another, so <ul>{items}</ul> shows the whole list:
export default function App() {
const items = topics.map((topic) => (
<li key={topic.id}>
Day {topic.day}: {topic.title} ({topic.minutes} min)
</li>
));
return (
<main>
<h1>Course topics</h1>
<ul>{items}</ul>
</main>
);
}The data lives in one place, the topics array. To add a topic, you add an
object to the array, not another <li> to the JSX. Add
{ id: 5, title: "Forms", day: 5, minutes: 90 } and run.
You'll usually see the map written straight inside the JSX:
<ul>
{topics.map((topic) => (
<li key={topic.id}>Day {topic.day}: {topic.title}</li>
))}
</ul>key={topic.id} gives each element a stable name. The next lesson explains
why React needs it.
filter, then map
To show only some items, filter the array first, then map what's left:
const long = topics.filter((topic) => topic.minutes > 90);Neither filter nor map changes topics. Each returns a new array.
That matters on Day 4's later lessons, where the array is state.
Predict
Replace the items line with this version, which uses curly braces instead of
round brackets after the arrow:
const items = topics.map((topic) => {
<li key={topic.id}>Day {topic.day}: {topic.title}</li>
});What does the page show?
Check your prediction
An empty list, and no error. An arrow function with { } is a block of
statements, and it returns nothing unless it says return. So map builds an
array of undefined, and React shows nothing for undefined. Use round
brackets, (topic) => ( <li>...</li> ), or write return inside the braces.
Your turn
Only the long days
Show a second list under the first, headed Longer than 90 minutes, with only
the topics whose minutes is more than 90. Show each as State (95 min).
npm install and npm run dev. Hint 1: the idea
filter first to keep the long topics, then map them to <li> elements.
Hint 2: a first step
You can chain them: topics.filter(...).map(...). Each <li> still needs a
key.
Show one solution
<h2>Longer than 90 minutes</h2>
<ul>
{topics
.filter((topic) => topic.minutes > 90)
.map((topic) => (
<li key={topic.id}>
{topic.title} ({topic.minutes} min)
</li>
))}
</ul>Completion is saved in this browser only. It does not measure mastery.