ReactJS Lists
The ReactJS render lists of items using the map()
function to iterate over an array and create React elements for each item. This is a common pattern for rendering dynamic content like a list of items fetched from an API or user-generated data. Here’s how you can work with lists in React:
1. Rendering Lists with map()
:
Assuming you have an array of data, you can use the map()
function to create React elements for each item in the array. For example, let’s say you have an array of names:
const names = ['John', 'Jane', 'Bob', 'Alice'];
You can render this list as follows:
import React from 'react';
function NameList() {
const names = ['John', 'Jane', 'Bob', 'Alice'];
const nameItems = names.map((name) => (
<li key={name}>{name}</li>
));
return (
<div>
<h2>List of Names</h2>
<ul>{nameItems}</ul>
</div>
);
}
export default NameList;
In this example:
- We use the
map()
function to iterate over thenames
array and create a list of<li>
elements, each containing a name. - We provide a unique
key
prop to each list item. React uses this key to efficiently update the list when changes occur.
2. Dynamic Lists:
You can render dynamic lists by mapping over an array of data or by fetching data from an API and using it to render a list of items. For instance, if you have an array of objects representing users:
const users = [
{ id: 1, name: 'John' },
{ id: 2, name: 'Jane' },
{ id: 3, name: 'Bob' },
];
You can render a list of users in a similar way:
import React from 'react';
function UserList() {
const users = [
{ id: 1, name: 'John' },
{ id: 2, name: 'Jane' },
{ id: 3, name: 'Bob' },
];
const userList = users.map((user) => (
<li key={user.id}>{user.name}</li>
));
return (
<div>
<h2>List of Users</h2>
<ul>{userList}</ul>
</div>
);
}
export default UserList;
In this example, we iterate over the users
array and create a list of <li>
elements displaying each user’s name.
React’s ability to efficiently update the DOM based on changes to your data makes it a powerful tool for rendering dynamic lists. The map()
function is a common approach for rendering lists in React, and it can be combined with various other techniques for more complex list rendering scenarios.