Fez Vrasta
Fez Vrasta

Reputation: 14835

Bind scope to event handler, but keep original argument

I bind an an event in this way:

render() {
  return <button onClick={this.click.bind(this)}>click me</button>
}

But I'd need to retrieve the original argument of the onClick event.

click(evt) {
  // evt is undefined here
  this.setState({ evt: evt })
}

How can I make this code work?

Upvotes: 0

Views: 174

Answers (1)

Davin Tryon
Davin Tryon

Reputation: 67316

To propagate the e from the click event you can wrap in another function:

render() {
  return <button onClick={function(e) { this.click(e)}.bind(this)}>click me</button>
}

Or, you can use arrow functions if you are in ES6:

render() {
  return <button onClick={(e) => { this.click(e)}}>click me</button>
}

Upvotes: 1

Related Questions