Reputation: 179
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": "[email protected]"
},
{
"id": 1,
"name": "John Smith",
"email": "[email protected]"
},
]
}
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
Upvotes: 2
Views: 2584
Reputation: 1
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)
}
Upvotes: 5
Reputation: 178
Just use this testClick={()=>testClick(person.id)}
and get Id of the clicked one in testclick function ;)
Upvotes: 2