Can you explain map() in react.js with example?

Can you explain map() in react.js with example?

In React, the .map() function is often used to show lists of elements. It lets you go through an array and make a new array of React elements using the values from the original array. Here are three examples of using .map() in React:

Example 1: Rendering a List of Strings

import React from 'react';

const StringList = () => {
  const strings = ['React', 'JavaScript', 'Components'];

  return (
    <ul>
      {strings.map((str, index) => (
        <li key={index}>{str}</li>
      ))}
    </ul>
  );
};

export default StringList;

In this example, we have a list of words (strings), and we use .map() to make a list of <li> items for each word. The key attribute is important for React to manage each item effectively.

Example 2: Rendering a List of Components

import React from 'react';

const PersonList = () => {
  const people = [
    { id: 1, name: 'Alice' },
    { id: 2, name: 'Bob' },
    { id: 3, name: 'Charlie' },
  ];

  return (
    <ul>
      {people.map((person) => (
        <li key={person.id}>{person.name}</li>
      ))}
    </ul>
  );
};

export default PersonList;

In this example, we have an array of objects called people. Each object represents a person with an id and a name. We use .map() to make a list of <li> elements that show each person's name.

Example 3: Dynamically Generating Components

import React from 'react';

const DynamicComponentList = () => {
  const components = [
    { type: 'button', text: 'Click me' },
    { type: 'input', placeholder: 'Type something' },
    // Add more component types as needed
  ];

  return (
    <div>
      {components.map((component, index) => {
        if (component.type === 'button') {
          return <button key={index}>{component.text}</button>;
        } else if (component.type === 'input') {
          return <input key={index} placeholder={component.placeholder} />;
        }
        // Add more conditions for other component types
        return null; // Handle unknown component types
      })}
    </div>
  );
};

export default DynamicComponentList;

In this example, we have an array of objects (components). Each object shows the type and properties of a dynamic component. We use .map() to create different types of components based on the array data.

Always give a unique key prop when using .map() so React can update the virtual DOM effectively.

Did you find this article valuable?

Support LingarajTechhub All About Programming by becoming a sponsor. Any amount is appreciated!