Introduction to Lists
In React, lists are used to render multiple components. You can use JavaScript arrays to create lists and render them in your components.Rendering Lists
To render a list in React, you can use the `map()` method to iterate over an array and return a JSX element for each item:
import React from 'react';
function NumberList(props) {
const numbers = props.numbers;
return (
<ul>
{numbers.map((number) => (
<li key={number.toString()}>{number}</li>
))}
</ul>
);
}const numbers = [1, 2, 3, 4, 5];
ReactDOM.render(
<NumberList numbers={numbers} />,
document.getElementById('root')
);In this example, the `NumberList` component renders a list of numbers.
Keys
When rendering lists, React requires a unique `key` prop for each item in the list. This helps React identify which items have changed, are added, or are removed.
<li key={number.toString()}>{number}</li>You can use a unique identifier from your data as the key, or a combination of properties that make the item unique.
Example Code
Here's an example of a simple React app that renders a list of items:
import React from 'react';function TodoList() {
const todos = [
{ id: 1, text: 'Buy milk' },
{ id: 2, text: 'Walk the dog' },
{ id: 3, text: 'Do laundry' },
];return (
<ul>
{todos.map((todo) => (
<li key={todo.id}>{todo.text}</li>
))}
</ul>
);
}
Here's a practice exercise:
Create a simple React app that displays a list of products. Each product should have a name and a price.
Hint: Use an array to store the products and the `map()` method to render the list. Use a unique `key` prop for each product.