Mapping Over Arrays to Render Components in React | Javascript

 import React from 'react';

const ListComponent = ({ items }) => {
  return (
    <ul>
      {items.map(item => (
        <li key={item.id}>{item.name}</li>
      ))}
    </ul>
  );
}

export default ListComponent;
 

AI Explanation

This code defines a functional React component called `ListComponent` that takes an `items` prop as an input. Inside the component, the `items` array is mapped over and each item is rendered as an `

  • ` element inside an `
      ` element. Key prop is used for each `
    • ` element to help React identify which items have changed, been added, or been removed. It is important to provide a unique key for each item in the array to help React efficiently update the UI without re-rendering unnecessary elements. Lastly, the `ListComponent` component is exported as a default export, which means it can be imported and used in other parts of the application.