DEV Community

Cover image for React Basics~map function/ a list of data~
Ogasawara Kakeru
Ogasawara Kakeru

Posted on

React Basics~map function/ a list of data~

  • When we want to display a list of data, how do we do?

・src/Example.js

const animals = ["Dog", "Cat", "Rat"];

const Example = () => {
  return (
    <>
      <ul>
        {/* Not using the map function. */}
        <li>{animals[0]}</li>
        <li>{animals[1]}</li>
        <li>{animals[2]}</li>
      </ul>
    </>
  );
};

export default Example;
Enter fullscreen mode Exit fullscreen mode
  • This code displays a list of data correctly.

・src/Example.js

const animals = ["Dog", "Cat", "Rat"];

const Example = () => {
  return (
    <>
      <ul>
        {/* Using the map function. */}
        {animals.map((animal) => (
          <li> {animal}</li>
        ))}
      </ul>
    </>
  );
};

export default Example;
Enter fullscreen mode Exit fullscreen mode
  • When we want to display a list of data, the Map function is often used to display an array of data like <li></li> element.

  • Please don't forget to put the key attribute on the<li></li> element.

  • This code is cleaner than the previous one.

・This is the console's warning, in case we don't put the key attribute on the <li></li> element.

Image description

・This is the result on the screen.

Image description

Reinvent your career. Join DEV.

It takes one minute and is worth it for your career.

Get started

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Engage with a sea of insights in this enlightening article, highly esteemed within the encouraging DEV Community. Programmers of every skill level are invited to participate and enrich our shared knowledge.

A simple "thank you" can uplift someone's spirits. Express your appreciation in the comments section!

On DEV, sharing knowledge smooths our journey and strengthens our community bonds. Found this useful? A brief thank you to the author can mean a lot.

Okay