Hello Sunil
render-lists-in-react-feature-image

How to Render Lists in React using map Method

When you are working with React, you will often times need to render lists of items.

In React, you can use the map() method to iterate over an array and create a list. Let’s see how to do that now.

What Is JavaScript map() Method?

The map() method is used for array transformation. It takes another custom function as an argument and on each array item applies that function.

Example:

const numbers = [1, 2, 3, 4, 5];

// Use map() to double each number in the array
const doubledNumbers = numbers.map((currentValue) => {
  return currentValue * 2;
});

console.log(doubledNumbers); // Output: [2, 4, 6, 8, 10]

In this example:

  • We have an array called numbers containing integers.
  • We use the map() method to create a new array called doubledNumbers.
  • Inside the map() function, we provide a callback that doubles each value in the original array.

Also Read: Quick Tutorial – JavaScript map Method 🚀

Now, let us see how we create a list in React. Below is an array you will be working with.

It contains info about applicants to a mentorship workshop. The array is stored in applicants variable.

const applicants = [
    {
      id: '0',
      name: 'Sunil',
      work: 'Freelance Developer',
      blogs: '54',
      websites: '32',
      hackathons: 'none',
      location: 'India',
    },
    {
      id: '1',
      name: 'Anil',
      work: 'Fullstack Developer',
      blogs: '34',
      websites: '12',
      hackathons: '6',
      location: 'India',
    },
		{
      id: '2',
      name: 'Gopal',
      work: 'Web Developer',
      blogs: '28',
      websites: '8',
      hackathons: '3',
      location: 'India',
    },
  ];

How map() Method Works in React

Now, you need to return JSX that renders every applicant name as presented from the array.

To get the names of the applicants, you can easily do that with JavaScript’s map() method. Below is how you can map every applicant’s name:

Applicants.jsx

import React from 'react';

const Applicants = () => {
  const applicants = [
    {
      id: '0',
      name: 'Sunil',
      work: 'Freelance Developer',
      blogs: '54',
      websites: '32',
      hackathons: 'none',
      location: 'India',
    },
    {
      id: '1',
      name: 'Anil',
      work: 'Fullstack Developer',
      blogs: '34',
      websites: '12',
      hackathons: '6',
      location: 'India',
    },
    {
      id: '2',
      name: 'Gopal',
      work: 'Web Developer',
      blogs: '28',
      websites: '8',
      hackathons: '3',
      location: 'India',
    },
  ];
  return (
    <div>
      <ul>
        {applicants.map(function (data) {
          return <li>Applicant Name: {data.name}</li>;
        })}
      </ul>
    </div>
  );
};

export default Applicants;

App.jsx

import Applicants from './Applicants';

function App() {
  return (
    <>
      <Applicants />
    </>
  );
}

export default App;

Output:

render-lists-react-example-1

Unfortunately, a quick inspection of our current webpage throws this error about keys:

Unfortunately, if we ran the above examples in our browser we might get an error in our console which says: “ Warning: Each child in a list should have a unique key prop “.

render-lists-react-example-2

This is one of the most common errors that show up while using react.

Warning: Each child in a list should have a unique key prop “.

What this error means is that in react whenever we render an item using the map() method, it should have a key prop and the value of the key prop should be unique for each item in the list.

Now, why do we need the key prop?

Why You Need Keys in Lists

We need a key prop because it helps react in finding which item in the list have been modified, updated, removed, or added, and through the key prop, react handles the UI updates efficiently.

Here is a code demo showing the key attribute at work:

Applicants.jsx

import React from 'react';

const Applicants = () => {
  const applicants = [
    {
      id: '0',
      name: 'Sunil',
      work: 'Freelance Developer',
      blogs: '54',
      websites: '32',
      hackathons: 'none',
      location: 'India',
    },
    {
      id: '1',
      name: 'Anil',
      work: 'Fullstack Developer',
      blogs: '34',
      websites: '12',
      hackathons: '6',
      location: 'India',
    },
    {
      id: '2',
      name: 'Gopal',
      work: 'Web Developer',
      blogs: '28',
      websites: '8',
      hackathons: '3',
      location: 'India',
    },
  ];

  return (
    <div>
      <ul>
        {applicants.map(function (data) {
          return <li key={data.id}>Applicant Name: {data.name}</li>;
        })}
      </ul>
    </div>
  );
};

export default Applicants;

As you can see, a large set of applicants is smoothly mapped and displayed using a few lines of code.

At the same time, if you were to delete applicants who did not meet some qualifications, the key attribute would help keep track of the remaining applicants using the unique assigned key.

This is the expected code output:

render-lists-react-example-4

In the above examples, you are only dealing with a single variable.

Now, there will be cases in your work where you will have different files and more than one variable in different React components.

This is where React props come in.

What are Props in React?

The word props stands for properties and they are used to pass data from one component to another in React.

The array we are using has a variable named applicants. You have a new component that showcases the applicants’ names, work, and their respective locations.

How then do you pass the list to this new component?

<ShowcaseApplicants applicants={applicants} />

You can easily get the applicants data from the props object as shown below:

App.jsx

import ShowcaseApplicants from './ShowcaseApplicants';

function App() {
  const applicants = [
    {
      id: '0',
      name: 'Sunil',
      work: 'Freelance Developer',
      blogs: '54',
      websites: '32',
      hackathons: 'none',
      location: 'India',
    },
    {
      id: '1',
      name: 'Anil',
      work: 'Fullstack Developer',
      blogs: '34',
      websites: '12',
      hackathons: '6',
      location: 'India',
    },
    {
      id: '2',
      name: 'Gopal',
      work: 'Web Developer',
      blogs: '28',
      websites: '8',
      hackathons: '3',
      location: 'India',
    },
  ];

  return (
    <>
      <h1>Oh! Hello World</h1>
      <ShowcaseApplicants applicants={applicants} />
    </>
  );
}

export default App;

Inside the the App component, we included applicants as a local variable. With that we don’t pollute the global scope. We then returned a React fragment with an h1 tag.

Next, we want to pass the data in the array to a new component that showcases further data about each applicant.

With the ShowcaseApplicants instantiation, the component accesses the array using the applicants props.

After that was done, we used map() method to map the applicants’ name, work, and location which was rendered as JSX. And we didn’t forget the important key attribute.

ShowcaseApplicants.jsx

import React from 'react';

const ShowcaseApplicants = (props) => {
  const applicants = props.applicants;

  return (
    <div>
      <ul>
        {applicants.map((data) => (
          <div key={data.id}>
            <li>Name: {data.name}</li>
            <li>Work: {data.work}</li>
            <li>Location: {data.location}</li>
          </div>
        ))}
      </ul>
    </div>
  );
};

export default ShowcaseApplicants;

Here is the expected code output:

render-lists-react-example-5

Index As Keys in Lists

In a case when a unique id or some other unique value is not present in our list we can also use the index as a key to preventing ourselves from the error in the console.

Applicants.jsx

import React from 'react';

const Applicants = () => {
  const applicants = [
    {
      name: 'Sunil',
      work: 'Freelance Developer',
      blogs: '54',
      websites: '32',
      hackathons: 'none',
      location: 'India',
    },
    {
      name: 'Anil',
      work: 'Fullstack Developer',
      blogs: '34',
      websites: '12',
      hackathons: '6',
      location: 'India',
    },
    {
      name: 'Gopal',
      work: 'Web Developer',
      blogs: '28',
      websites: '8',
      hackathons: '3',
      location: 'India',
    },
  ];

  return (
    <div>
      <ul>
        {applicants.map(function (data, index) {
          return <li key={index}>Applicant Name: {data.name}</li>;
        })}
      </ul>
    </div>
  );
};

export default Applicants;

App.jsx

import Applicants from './Applicants';

function App() {
  return (
    <>
      <Applicants />
    </>
  );
}

export default App;

Here is the expected code output:

render-lists-react-example-4

But while adding new items to the start of the list the problem will still persist similar to the condition when we had no key, this can be because by default React uses the index as the key.

But still, we can use the index as key if and only if:

  • Items do not have a unique value.
  • List is static.
  • List won’t be filtered or re-ordered.

Conclusion

In this article you have learned how to use the JavaScript map() method to render a list of items in React. You also learned how to use React props to pass the lists data into other components as well.

Finally we also saw how to use Index as keys in lists.

Resource

How useful was this post?

Click on a star to rate it!

Average rating 0 / 5. Vote count: 0

No votes so far! Be the first to rate this post.

We are sorry that this post was not useful for you!

Let us improve this post!

Tell us how we can improve this post?

Similar articles you may like

Sunil Pradhan

Hi there đź‘‹ I am a front-end developer passionate about cutting-edge, semantic, pixel-perfect design. Writing helps me to understand things better.

Add comment

Stay Updated

Want to be notified when our article is published? Enter your email address below to be the first to know.

Sunil Pradhan

Hi there đź‘‹ I am a front-end developer passionate about cutting-edge, semantic, pixel-perfect design. Writing helps me to understand things better.