1. From Data to UI 📜
In web development, a common task is to take an array of data (e.g., from a database or an API) and display it as a list. You might have an array of user objects, and you want to render a profile card for each user.
React makes this process straightforward by relying on a standard JavaScript feature: the .map() array method.
2. Using JavaScript's .map() Method
The .map() method is perfect for this job. It creates a **new array** by transforming every item in an original array. In our case, we will transform an array of data (like strings or objects) into an array of React elements (JSX).
You can embed a .map() call directly within your JSX using curly braces `{}`.
function TodoList() {
const todos = [
'Learn JSX',
'Learn Components',
'Learn State'
];
return (
<div>
<h2>My Todos</h2>
<ul>
{/* We map over the todos array */}
{todos.map(todoText => (
// For each item, we return an <li> element
<li>{todoText}</li>
))}
</ul>
</div>
);
}
React will run this code, see the array of `
3. The Importance of the `key` Prop 🔑
If you run the code above, your browser's console will show a warning: "Each child in a list should have a unique 'key' prop."
A **`key`** is a special string attribute you need to include when creating lists of elements. Keys help React identify which items have changed, are added, or are removed. This allows React to update the UI more efficiently.
Rules for Keys:
- Keys must be **unique** among siblings in the list.
- Keys should be **stable**. They shouldn't change between re-renders.
Often, your data will have a unique `id` field from a database. This is the perfect value to use as a key. If you don't have a stable ID, you can use the item's index in the array as a last resort, but it's not ideal if the list can be reordered.
Corrected Example with Keys:
function UserList() {
const users = [
{ id: 'u1', name: 'Alice' },
{ id: 'u2', name: 'Bob' },
{ id: 'u3', name: 'Charlie' }
];
return (
<ul>
{users.map(user => (
// The key is placed on the outermost element in the map
<li key={user.id}>
{user.name}
</li>
))}
</ul>
);
}