Search code examples
reactjsreact-map-gl

Map method in ReactJS


items.map((itemsvalue, index) => {
  return (
    <>
      <li key={index}>
        <button className="deleteBtn" onClick={DeleteBtn}>
          X
        </button>
        {itemsvalue}
      </li>
    </>
  );
});

Here items is an array of strings. How can i access index value in the DeleteBtn function???


Solution

  • You can pass an inline function for the onClick handler. I have changed function name to onClickDelete , because its a common practice to name the click handlers as onClickDelete, handleDelete .

    items.map((itemsvalue, index) => {
      return (
        <>
          <li key={index}>
            <button className="deleteBtn" onClick={() => onClickDelete(index)}>
              X
            </button>
            {itemsvalue}
          </li>
        </>
      );
    });