alanbuchanan alanbuchanan - 9 months ago 40
Javascript Question

Passing a value into a method that is triggered by an event

I made a simple todo app using React.

An unordered list (

is used to present all the items in my list. Within that are list items (
), and with a list item is a button with an
handle attached to a class method:

<button onClick={this.onHandleClick.bind(this)}>Add</button>

In the method, I need to prevent the default behaviour to prevent the page refreshing when the button is clicked:

onHandleClick(event) {

My question is, what can I do if I want to pass a value into
, given that
is given as the argument?

Answer Source

Wrap your event handler in another function and pass item specific parameters this way:

<button onClick={e => this.handleClick(e, itemId)}>Add</button>

handleClick(event, itemId) {