Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get the id of a button that was clicked? ReactJS

I was wondering how I would go about getting the id (becuase it is unknown) of a button that is clicked. So when the button is clicked, I know what the id of that specific button is. There are lots of buttons on the page and I would like to know which button is pressed (they all have unique id's). Currently the buttons look like this:

  <button key={uuidv4()} id={this.props.keyword} value={this.props.keyword} onClick={this.props.onClick} className="removeButton">Remove</button>
like image 431
dorkycam Avatar asked Aug 14 '18 17:08

dorkycam


4 Answers

I know this has already been answered but i was working with react and faced similar issue, lost 2 hours trying to figure out why event.target.id was sometimes null or an empty string

this solved it for me:

class Button extends React.Component {

    getButtonId = (e) => {
      console.log(e.currentTarget.id);
    }

    render() {
       return (
          <button id="yourID" onClick={this.getButtonId}>Button</button>
       );
    }
}
like image 168
davyCode Avatar answered Oct 26 '22 00:10

davyCode


Well if the elements are nested event.target won't always work since it refers to the target that triggers the event in the first place. See this link for the usage of event.currentTarget, which always refer to the element that the handler is bound to.

Another way to grab hold of the element and its attributes is to use React refs. This is more general when trying to get the DOM element in React.

like image 25
Kevin He Avatar answered Oct 25 '22 23:10

Kevin He


The very convenient way (not only for buttons but for list of elements) to do this is using custom attribute data-someName of DOM element and then reach it via event.currentTarget.dataset.someName

const openCard = (event) => {
  console.log('event.currentTarget.dataset.id', event.currentTarget.dataset.id); // >> id
  //do more actions with id
};

<Card onClick={openCard} data-id={item.id}>
  <CardContent />
</Card>;

`

like image 36
Sandra Avatar answered Oct 26 '22 00:10

Sandra


if the function to handle the event is in the same component it is best to use the event.target.id, this will have its limitations when you try accessing a DOM element nested as a child component as event.target.id. Use event.currentTarget.id is nested,

This happens because event.currentTarget can identify the element that caused the event deep down from the child as it burbles out, while event.target.id will set the target as the child component and will not be able to identify the child component that has that element since it target does not change and hence faulty.

You can watch this youtube video to understand better. also read from their differences

like image 35
Yagi91 Avatar answered Oct 26 '22 00:10

Yagi91