Iterating and rendering data with React

Published January 16 2021

Updated January 16, 2021

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.

export class MyList extends React.Component {
  render() {
    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.

export class MyList extends React.Component {
  render() {
    const usernames = ['Mario', 'Luigi', 'Bowser']; // let's mock data from an API
    
    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.

export class MyList extends React.Component {
  render() {
    const usernames = ['Mario', 'Luigi', 'Bowser']; // let's mock data from an API
    const listItems = [];

    for (const username of usernames) {
      listItems.push(<li key={username}>{username}</li>)
    }

    return (
      <div>
        {listItems}
      </div>
    );
  }
}

With the looping code that builds the listItems now out of the return statement, we can easily extract this logic to a separate file that can be re-used across multiple components.

You have now become an expert on how to iterating and render data in React. Go forward iterating and rendering with confidence!