Complete the code to add a unique key to each list item in React.
const items = ['apple', 'banana', 'cherry']; return ( <ul> {items.map(item => <li [1]={item}>{item}</li>)} </ul> );
In React, the key prop uniquely identifies elements in a list to help React update efficiently.
Complete the code to use the array index as the key in a React list (not recommended but valid).
const fruits = ['mango', 'pear', 'grape']; return ( <ul> {fruits.map((fruit, [1]) => <li key=[1]>{fruit}</li>)} </ul> );
The second argument of map is the index, which can be used as a key, though it's better to use unique IDs.
Fix the error in the code by adding the correct key prop to the list items.
const tasks = [{id: 1, name: 'Clean'}, {id: 2, name: 'Cook'}];
return (
<ul>
{tasks.map(task => <li [1]={task.id}>{task.name}</li>)}
</ul>
);The key prop must be used to uniquely identify list items in React, not id or others.
Fill both blanks to create a list of buttons with unique keys and labels.
const buttons = ['Save', 'Cancel', 'Delete']; return ( <div> {buttons.map((btn, [1]) => <button key=[1]>[2]</button>)} </div> );
The index is used as the key, and the button label is the btn variable.
Fill all three blanks to create a list of user names with unique keys using user IDs.
const users = [{id: 101, name: 'Alice'}, {id: 102, name: 'Bob'}];
return (
<ul>
{users.map([1] => <li key=[2]>[3]</li>)}
</ul>
);We name the map parameter user, use user.id as the key, and display user.name.