Rendering and data flow
Render a list with map
Turn an array of data into an array of elements or components.
Transform data into elements with map():
function TaskList({ tasks }) {
return (
<ul>
{tasks.map(task => (
<li key={task.id}>{task.title}</li>
))}
</ul>
)
}
React renders each returned element as a sibling. The key helps React match each task with its previous element on the next render.
Filter data before mapping when the interface shows a subset:
const openTasks = tasks.filter(task => !task.done)
Keep the transformation pure. Do not delete tasks, update state, or sort the original state array while rendering. Copy before sorting:
const sortedTasks = [...tasks].sort(compareTasks)
Render a useful empty state when the array contains nothing. An empty ul often gives no explanation.
When a list item grows, extract a Task component and pass the item plus intent callbacks. Keep the key on the element returned directly from map().
Add, remove, and reorder tasks. The displayed order should come entirely from the array used by this render.
Lesson completed