CodeBlanks Logo Icon CodeBlanks

Summary - List rendering

Write a storefront that sorts a product list by price and shows it.

Summary - List rendering

In this group you learned to draw arrays. Three steps: transform with map, give a unique identity with key, optionally filter with filter.

The key always sits on the outermost node and must be unique among siblings. The best key is the id field; the index only works for append-only lists.

Splitting the list into a child makes the code readable: the parent calls map, the child draws one item.

Practice List summary task

Complete the skeleton. Write a TodoList component. The todos array has id, text and done on each item. Use filter to keep only items where !todo.done, then map them into <li key={todo.id}>{todo.text}</li>. Export it.

Starter code

App.jsx
// Define TodoList here

Sample solution

App.jsx
function TodoList() {
  const todos = [{ id: 1, text: "Buy milk", done: false }, { id: 2, text: "Buy bread", done: true }];
  return <ul>{todos.filter(t => !t.done).map(todo => <li key={todo.id}>{todo.text}</li>)}</ul>;
}

export default TodoList;

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Which is wrong?

App.jsx
A random key refreshes every render.
  • key must be unique among siblings
  • Math.random() is the best key Correct answer
  • map returns a new array
  • filter does not mutate

Explanation: Math.random() changes every render; it is a bad choice.

2 Summary - List rendering: match the terms

Term Meaning
map Transforms
key Gives identity
filter Filters
sort Sorts

All lessons in Beginner