How to target single item in list with onclick when mapping in reactjs

When mapping a list in ReactJS and wanting to target a single item with an `onclick` event, you can achieve this by passing a unique identifier (such as an index or ID) to the event handler function.

Here’s an example:

import React from 'react';

const MyComponent = () => {
  const myList = ['Item 1', 'Item 2', 'Item 3'];

  const handleItemClick = (index) => {
    console.log('You clicked on', myList[index]);
  };

  return (
    
{myList.map((item, index) => ( <div key={index} onClick={() => handleItemClick(index)} > {item} </div> ))}
); }; export default MyComponent;

In this example, we have an array called `myList` with three items. We use the `map` function to iterate over the list and render a `div` element for each item. The `key` prop is set to the `index` of each item to ensure React can track them properly.

In the `onClick` event handler of each `div`, we pass the `index` to the `handleItemClick` function. By doing this, we can identify which item was clicked and perform any desired actions.

In the `handleItemClick` function, you can do whatever you need with the clicked item. In this example, we simply log the clicked item to the console.

Leave a comment