Search code examples
reactjsarrow-functions

ReactJS - Passing ID through OnClick


I want to pass the 'ID' and 'Value' of a <button> into a function, and use it to run a piece of code. I was not able to pass the elements. I have tried the several solutions mentioned in similar questions, but was unsuccessful.

I ended up passing them as parameters, and everything works fine. But I know there must be way to do this better, by passing the ID and Value, without having to pass it as hard-coded parameters.

<button type="button" id="button1" name="testName" value="abc" onClick={()=>this.callFunction('button1', 'abc')}>Click Me !!</button>

callFunction(id,value) {
  console.log(id,value);
}

Solution

  • As mentioned in comments

    Use event to get the id. Pass event to the handler function and get the id value with event.target.id

    <button type="button" id="button1" name="testName" value="abc" onClick={event => this.callFunction(event)}>Click Me !!</button>
    
    callFunction = (event) => {
       console.log(event.target.id, event.target.value);
    }