0
0
Reactframework~30 mins

Importance of keys in React - See It in Action

Choose your learning style9 modes available
Importance of keys in React lists
📖 Scenario: You are building a simple React app that shows a list of fruits. Each fruit has a unique ID and a name.In React, when you create lists, you need to give each item a special key so React can keep track of them efficiently. This helps React update only the changed items when the list changes, like when you add or remove fruits.
🎯 Goal: Build a React functional component that renders a list of fruits using the map() method. Assign a unique key prop to each list item using the fruit's id.
📋 What You'll Learn
Create a list of fruit objects with id and name properties
Create a React functional component named FruitList
Use the map() method to render each fruit inside an unordered list <ul>
Assign the key prop to each <li> using the fruit's id
💡 Why This Matters
🌍 Real World
React apps often display lists of items like products, messages, or users. Using keys helps React update these lists quickly and correctly.
💼 Career
Understanding keys is essential for React developers to build efficient and bug-free user interfaces that handle dynamic lists.
Progress0 / 4 steps
1
Create the fruit data array
Create a constant array called fruits with these exact objects: { id: 1, name: 'Apple' }, { id: 2, name: 'Banana' }, and { id: 3, name: 'Cherry' }.
React
Need a hint?

Use const fruits = [ ... ] with the exact objects inside.

2
Create the FruitList component
Create a React functional component named FruitList that returns an empty unordered list <ul>.
React
Need a hint?

Define function FruitList() and return an empty <ul> element.

3
Render the fruit names with map()
Inside the FruitList component's <ul>, use fruits.map() with parameters fruit to create a list item <li> for each fruit. Display the fruit's name inside each <li>.
React
Need a hint?

Use fruits.map(fruit => ( ... )) and return <li>{fruit.name}</li>.

4
Add unique key prop to each list item
Add a key prop to each <li> inside the map() using fruit.id as the key.
React
Need a hint?

Add key={fruit.id} inside the <li> tag.