Iterating and rendering data in React components
When building a React application, iterating over data to display it is a common need. When we know what our data items will be in advance, we can easily hard-code them directly into the HTML like in the example below.
const MyList = () => {
return (
<ul>
<li>Mario</li>
<li>Luigi</li>
<li>Bowser</li>
</ul>
);
}
However, when we are dealing with dynamic data, we don't know in advance what the value of our data items will be and so we cannot hard-code them. This dynamic data could be returned from an API that we are fetching from. Let's look at two approaches for iterating over and rendering dynamic data.
1. Iterate and render in the return statement
When dealing with dynamic data, the first approach is to use the JavaScript map
method to render the data items directly in the return statement of the render function.
const MyList = () => {
// let's mock data from an API
const usernames = ['Mario', 'Luigi', 'Bowser'];
return (
<ul>
{usernames.map(username => {
return <li key={username}>{username}</li>
})}
</ul>
);
}
Use the key attribute to ensure that each looped element is uniquely identified. This helps React to identify which items have changed in the list. Always add keys when rendering items in an iterable list. A key should uniquely identify a list item from other list items.
2. Iterate and render an array of JSX elements
When dealing with dynamic data, the better approach is to loop over that data to add JSX elements to an array that can then be rendered separately. The first approach that we saw above is fine for a simple component. However, as components grow in size, it's best to keep return statements as simple as possible.
const MyList = () => {
// let's mock data from an API
const usernames = ['Mario', 'Luigi', 'Bowser'];
const listItems = usernames.map(username => {
return (
<li key={username}>{username}</li>
);
});
return (
<ul>
{listItems}
</ul>
);
}
With the looping logic that builds the listItems now out of the return statement, we have a simpler return statement and a more organized component.
If the logic for building listItems happens to be needed in other components too, we can now easily extract the listItems logic to a helper file.
Conclusion
The two strategies we covered in this article will help you iterate and render data in React. You can now iterate and render data in React with confidence.