Conceptual Article

Understanding How To Render Arrays in React

Updated on July 27, 2020
Default avatar

By joshtronic

English
Understanding How To Render Arrays in React

Introduction

This article will teach you how to render an array in React and the best practices to use when rendering different elements within components.

One of the advantages of using a modern web language like JavaScript is that you can quickly automate the generation of HTML chunks.

Using something like a loop against an array or an object means you only have to write the HTML per item one time. Better yet, any future edits only have to be applied once.

Rendering Multiple Elements

To render multiple JSX elements in React, you can loop through an array with the .map() method and return a single element.

Below, you loop through the reptiles array and return a li element for each item in the array. You can use this method when you want to display a single element for each item in the array:

function ReptileListItems() {
  const reptiles = ["alligator", "snake", "lizard"];

  return reptiles.map((reptile) => <li>{reptile}</li>);
}

The output will look like this:

Output
- alligator - snake - lizard

In the next example, you will examine why you would want to add a unique key to a list of elements rendered by an array.

Rendering a Collection of Elements Inside a Component

In this example, you loop through an array and create a series of list item components like the previous example.

To start, update the code to use the <ol> component to hold the <li> items. The <ol> component will create an ordered list of the items:

function ReptileList() {
  const reptiles = ["alligator", "snake", "lizard"];

  return (
    <ol>
      {reptiles.map((reptile) => (
        <li>{reptile}</li>
      ))}
    </ol>
  );
}

However, if you look at the console, you will see a warning that each child in an array or iterator should have a unique key.

Warning in console

The warning appears because when you attempt to render a collection inside a component, you must add a key.

In React, a unique key is used to determine which of the components in a collection needs to be re-rendered. Adding a unique key prevents React from having to re-render the entire component each time there is an update.

In this step, you will render multiple elements in a component and add a unique key. Update the code to include a key on the list items to resolve the warning:

function ReptileList() {
  const reptiles = ['alligator', 'snake', 'lizard'];

  return (
    <ol>
      {reptiles.map(reptile => (
        <li key={reptile}>{reptile}</li>
      ))}
    </ol>
  );
}

Now that you’ve added in a key, the warning will no longer be in the console.

In the next example, you will see how to render adjacent elements without encountering a common syntax error.

Rendering Adjacent Elements

In JSX, to render more than one element in a component you must add a wrapper around them.

In this example, you will first return a list of items without looping through an array:

function ReptileListItems() {
  return (
    <li>alligator</li>
    <li>snake</li>
    <li>lizard</li>
  );
}

This will give you a hard error in the console:

Hard error from React for Adjacent JSX elements

To fix this error you need to wrap the block of li elements in a wrapper. For a list you can wrap them in an ol or ul element:

function ReptileListItems() {
  return (
  <ol>
    <li>alligator</li>
    <li>snake</li>
    <li>lizard</li>
  </ol>
  );
}

The adjacent <li> elements are now wrapped in an enclosing tag, <ol>, and you will no longer see an error.

In the next section, you will render a list in a wrapper using a fragment component.

Rendering Adjacent Elements with React.fragment

Prior to React v16.2, you could wrap a block of components in a <div> element. This would lead to an application full of divs, often referred to as “div soup”.

To fix this issue, React released a new component known as the fragment component:

When you need to render a list inside an enclosing tag but want to avoid having to use a div, you can use React.Fragment instead:

function ReptileListItems() {
  return (
  <React.Fragment>
     <li>alligator</li>
     <li>snake</li>
     <li>lizard</li>
  </React.Fragment>
  );
}

The rendered code will only include the li elements and the React.Fragment component will not appear in the code.

JSX elements rendered inside a React.Fragment wrapper

Also, note with React.fragment there is no need to add a key.

You may notice writing React.fragment is more tedious than adding a <div>. Fortunately, the React team developed a shorter syntax to represent this component. You can use <> </> in place of <React.Fragment></React.Fragment>:

function ReptileListItems() {
  return (
 <>
    <li>alligator</li>
    <li>snake</li>
    <li>lizard</li>
 </>
  );
}

Conclusion

In this article, you explored various examples of how to render arrays in a React application.

When rendering an element inside another component, you should use a unique key and wrap your elements inside a wrapper element.

Depending on your use case, you can create simple lists wrapped in a fragment component that does not need a key.

To learn more about best practices in React, follow the full How To Code in React.js series on DigitalOcean.

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about us


About the authors
Default avatar
joshtronic

author



Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
Leave a comment


This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

Try DigitalOcean for free

Click below to sign up and get $200 of credit to try our products over 60 days!

Sign up

Join the Tech Talk
Success! Thank you! Please check your email for further details.

Please complete your information!

Get our biweekly newsletter

Sign up for Infrastructure as a Newsletter.

Hollie's Hub for Good

Working on improving health and education, reducing inequality, and spurring economic growth? We'd like to help.

Become a contributor

Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

Welcome to the developer cloud

DigitalOcean makes it simple to launch in the cloud and scale up as you grow — whether you're running one virtual machine or ten thousand.

Learn more
DigitalOcean Cloud Control Panel