I want to identify which row was clicked using React.js map function. I have a list where data coming from API. Now I have a delete and edit button with each row. How can I find on which row I clicked?
Demo: https://codesandbox.io/s/map-delete-edit-jeuyfz?file=/src/App.js
My code:
import React, { useState } from "react"; import { Button} from "@mui/material"; import "./styles.css"; const data =[ { "title": "title1", "IsActive": 1 }, { "title": "title2", "IsActive": 0 }, { "title": "title3", "IsActive": 1 }, { "title": "title4", "IsActive": 1 } ] export default function App() { const [data2, setData2] = useState(data); const deleteHandle = (i) =>{ console.log(i); } return ( <div className="App"> {data2 ? data2.map((val, i) => ( <div className="box" key={i}> <h2>{val.title}</h2> <Button onClick={deleteHandle}>Delete</Button> <Button>Edit</Button> </div> )) : ""} </div> ); }
titleorindexor w/e as<Button onClick={()=>deleteHandle(val.title, i)}>Delete</Button>val.titlein click function?const deleteHandle = (arg1, arg2 .... ) =>{ ... }where they are passed as<Button onClick={()=>deleteHandle(arg1, arg2, ....)}>Delete</Button>you can pass event as<Button onClick={(e)=>deleteHandle(e, arg1, arg2, ....)}>Delete</Button>