Lists Keys and Conditional Rendering
Render arrays of elements with .map(), supply stable key props, and conditionally render elements with && and the ternary operator.
Rendering Lists with .map()
Render a dynamic list by calling .map() on an array and returning JSX for each item. React renders an array of elements just like a single element.
const fruits = ['apple', 'banana', 'cherry'];
return (
<ul>
{fruits.map(fruit => (
<li key={fruit}>{fruit}</li>
))}
</ul>
);The key Prop — Why It Matters
key is a special React prop that helps it identify which items in a list have changed, been added, or removed. Without keys (or with unstable keys like indices), React may produce incorrect updates.
All lessons in this course
- JSX: Syntax and Transpilation
- Functional Components and Props
- useState Hook: State and Re-renders
- Lists Keys and Conditional Rendering