11

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>
dorkycam
  • 479
  • 4
  • 11
  • 25

10 Answers10

13

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.

Kevin He
  • 1,210
  • 8
  • 19
11

You can use event.target.id to get the ID of button clicked

class App extends React.Component {
  constructor(props) {
    super(props);
    this.handleClick = this.handleClick.bind(this);
  }
  handleClick(event) {
    const id = event.target.id;
    console.log(id);
  }
  render() {
    return (
      <button id="unique-id" onClick={this.handleClick}>Button</button>
    );
  }
}
ReactDOM.render(<App />, document.getElementById("root"));
<script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<div id="root"></div>
Agney
  • 18,522
  • 7
  • 57
  • 75
8

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>
       );
    }
}
davyCode
  • 399
  • 4
  • 4
6

You can use either event.target.[selector goes here] or event.currentTarget.[selector goes here] to solve your issue. See example code below.

class Button extends React.Component {

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

  render() {
    return (
      <button id="yourID" onClick={this.handleId}>Button</button>
    );
  }
}
5

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>;

`

Sandra
  • 439
  • 4
  • 3
2

There is several way to do this

  1. With manipulating onClick function

 <button key={uuidv4()} id={this.props.keyword} value={this.props.keyword} onClick={(e)=>this.props.onClick(e,this.props.keyword)} className="removeButton">Remove</button>
    
onClick = (e,id) =>{
    console.log(id);
}
  1. Without manipulating onClick function

<button key={uuidv4()} id={this.props.keyword} value={this.props.keyword} onClick={this.props.onClick} className="removeButton">Remove</button>

onClick = (e) =>{
  const id = e.target.getAttribute("id");
  console.log(id);
}
Nishant Dixit
  • 5,388
  • 5
  • 17
  • 29
  • 1
    When I tried this out I got a `TypeError: Cannot read property 'target' of undefined` error – dorkycam Aug 14 '18 at 17:41
  • Maybe it's because the button and onClick handler are in different components? (things are being passed as props) – dorkycam Aug 14 '18 at 17:41
  • If onClick is working then you should get `e`, can you replace it with this `onClick={(e)=>this.props.onClick(e)}` and let me know? – Nishant Dixit Aug 14 '18 at 17:44
  • Strange because In above comment I was suggested you to pass `e` manually In this case `function` should have got `e`, can you describe more what exactly happening behind the scene? – Nishant Dixit Aug 14 '18 at 17:53
  • So I have an `App` component that's a parent to a `WordTable` component that's a parent to a `Row` component that renders each button (along with other things in the row) `WordTable` takes in info from a JSON file and generates a row for every object in that file (along with this button). This button is supposed to be able to remove the row from the table and item from the JSON file – dorkycam Aug 14 '18 at 19:09
  • "id" happens to be "undefined" in first approach. Why? – OwlR Jul 30 '23 at 22:00
1

You can do this:

function getId(id) {
  console.log(id);
}
<button key={uuidv4()} id={this.props.keyword} value={this.props.keyword} onClick="getId(this.id)" className="removeButton">Remove</button>
1

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

Yagi91
  • 35
  • 6
  • to ellaborate `event.target.getAttribute('attribute_name')` will cover a wider range of scenarios – Yagi91 Nov 25 '21 at 23:40
0

Your onClick handler should receive the click event, which should include the id: event.target.id.

<button
  key={uuidv4()}
  id={this.props.keyword}
  value={this.props.keyword}
  onClick={(event) => /* you want to use event.target.id */}
  className="removeButton">Remove</button>
Danny Delott
  • 6,756
  • 3
  • 33
  • 57
0

This worked for me:

functionName = (event) => {
    const id = event.target.id;
    const value = event.target.value;
    console.log("Value of the button: ", value)
    console.log("Id of the button: ", id)}