Test your skills on rendering lists in React with this quiz, focusing on using the map() function and understanding the importance of keys and best practices!
Question 1
What is the purpose of the map() function in React?
To map the state of a component to the DOM
To convert a list of elements into an array
To create a new array by applying a function to each element of an array
To filter elements based on a condition
Question 2
What is the role of keys in lists in React?
To identify the list items uniquely
To render lists faster
To update the component when state changes
To ensure proper indexing of array elements
Question 3
Which of the following is the best practice when assigning keys in a list in React?
Using the index of the array
Using a random number generator
Using a unique identifier for each item
Using a string of text
Question 4
How can you render a list of items in React using JSX?
<ul>{items.map(item => <li>{item}</li>)}</ul>
<ul><map>{items}</map></ul>
<ul>{map(item => <li>{item}</li>)}</ul>
<ul>{items}</ul>
Question 5
What happens if you don't assign keys to list elements in React?
React will throw an error
React will render the list but might not optimize the update process
The list will not render
React will assign random keys automatically
Question 6
What is the issue with this code in terms of key assignment?
const list = ["apple", "banana", "cherry"];
return (
<ul>
{list.map((fruit, index) => (
<li key={index}>{fruit}</li>
))}
</ul>
);
Using index as a key is fine in all cases
index should not be used as a key when the list can change dynamically
The key should always be a string
key should be assigned to the ul tag
Question 7
Which of the following is the correct syntax for rendering a list of components with unique keys in React?
{list.map(item => <Component key={item.id} />)}
{list.map(<Component key={item.id} />)}
{list.map(Component => <key={item.id} />)}
{list.map(<key={item.id}>Component</key>)}
Question 8
What is the output of the following code?
const items = ['Apple', 'Banana', 'Apple'];
return (
<ul>
{items.map((item, index) => <li key={index}>{item}</li>)}
</ul>
);
A list with duplicate keys
A list with unique keys
A list with no keys
An error due to duplicate keys
Question 9
What is the key used in this example?
const users = [{id: 1, name: 'Alice'}, {id: 2, name: 'Bob'}];
return (
<ul>
{users.map(user => <li key={user.id}>{user.name}</li>)}
</ul>
);
user.name
user
user.id
index
Question 10
In which of the following cases is it acceptable to use the index of an array as the key?
When the list is static and doesn't change
When the list is sorted alphabetically
When the list contains unique values
When the list is dynamically generated
There are 10 questions to complete.