alanbuchanan alanbuchanan - 15 days ago 5
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 (

<ul>
is used to present all the items in my list. Within that are list items (
<li>
), and with a list item is a button with an
onClick
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) {
event.preventDefault();
...
}


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

Answer

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) {
    event.preventDefault();
    console.log(itemId);
}
Comments