Varun Nair
Varun Nair

Reputation: 349

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

Upvotes: 0

Views: 138

Answers (3)

Idan
Idan

Reputation: 5450

You can use event, check handling events

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

or

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

In callFunction you can call the read the event:

callFunction = (event) => {
  const id = event.target.id;
  const value = event.target.value;
}

Upvotes: 1

Hemadri Dasari
Hemadri Dasari

Reputation: 33984

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

Upvotes: 1

Steve Holgado
Steve Holgado

Reputation: 12071

You can use the event target, e.target:

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

callFunction(e) {
  console.log(e.target.id, e.target.value)
}

Upvotes: 3

Related Questions