ReactJS event works sometimes, sometimes doesn't

Viewed 117

I am trying to get the id of the button clicked in React and this is the code I've written:

 const saveid = (e) => {
  console.log(e.target.id);
}
<Button className='gettheid'  onClick={(e)=>saveid(e)} id={something[i][0]} variant="contained" color="primary">

The console.log I've written in saveid sometimes gives the id but sometimes it doesn't. I am unable to figure out why. Can someone help me out

1 Answers

It looks like you need currentTarget instead because every time you click on button it won't be a target button, it can be it's child node also. So, in this case it is going to fail.

So, I can suggest you to use currentTarget this is always be your element which is bound to the event.

e.currentTarget.id
Related