JS: how to telly which button has been clicked

If you have several buttons, each of which calls the same method (onClick = {this.handleClick}), but you want to know which button in particular was pressed (within the handleClick method), how is this done?

You can add a unique id attribute to each button and then access that id on click.

I’ve tried something like the following, but without success:

<button id = "button1" onClick = {this.handleClick(id)}></button>

clickHandler(x){ console.log("value passed was ' + x) }

Can I see more of your code? Have you bound handleClick properly?

Keep in mind, that x will be the event object passed to the method when triggered.

Does that mean I can access id by saying: event.target.value in the method, if i pass the id in the method call? I did bind the method using the normal this.method=this.method.bind(this)

You can just access the id like:

  console.log("id of element is ' + event.target.id)

Thanks for that. That’s a great help.