React.js - Finding ID of a mapped element on click event

Viewed 1204

I'm trying to find the id of the current element, so that when i do an onClick, i can manipulate just the mapped element I have clicked.

test onClick

const testClick = (event) => {
    console.log(event.person.id)
}

data:

{
  "ExampleData": [
    {
      "id": 0,
      "name": "Joe Doe",
      "email": "joedoe@gmail.com"
    },
    {
      "id": 1,
      "name": "John Smith",
      "email": "johnsmith@example.com"
    },
]

}

mapping:

const data = exampleData.ExampleData

 {(data|| {}).map((person, i) => {
                return (
                    <DataContainer testClick={testClick} person={person}/>
                )
            })}

that maps the DataContainer child as many times as there are items in the array of objects.

But now, I'm trying to have an onClick that detects the specific mapped item i have pressed. As youy can see I'm passing the testClick function to DataContainer, and inside there I'm trying console log the current ID of the user I have pressed.

const testClick = (e) => {
    console.log(e.id)
}

For example:

onClick - if ID === currentID --- do something 
2 Answers

add an arrow function as handler for the click event and pass the id as parameter :

 testClick={()=>testClick(person.id)}

if you need also the event you could do :

 testClick={(event)=>testClick(event,person.id)}

and

 const testClick = (event,id) => {
   console.log(event, id)
}

Just use this testClick={()=>testClick(person.id)} and get Id of the clicked one in testclick function ;)

Related