2

So, I've been looking around for the correct way to pass both a parameter object and the event object to an event handler in react. Is there a best practise?

The only way I found is to use an arrow function and pass in both the event object and the parameter, like this.

<Button onClick={(e) => this.updateProgress(e, 1)} >Increase</Button>

Which is discouraged by the official documentation due to the possibility of multiple callback bindings in some scenarios.

https://facebook.github.io/react/docs/handling-events.html

Is there a way to pass along both the event object and an event args object to the event handler without using an arrow function?

3
  • Yeah you can call a function which would call another function with the argument. That would be even more messier Commented Mar 5, 2017 at 12:39
  • @ArshabhAgarwal I saw a blog post with that pattern, looked messy. Commented Mar 5, 2017 at 20:33
  • Yes! Just do what you are doing now. The answer below is quite correct. Commented Mar 5, 2017 at 20:36

2 Answers 2

4

I've never it actively discouraged. The part of the documentation you are referring to is when you aren't passing extra arguments.

When you are passing arguments, the way you have presented is exactly the way to do it.

Edit The exception would be if the arguments are somehow constants (I can't think of a case when they would be, just flagging).

This pattern (the one you presented) is important especially for handlers within loops, where each item needs to call a callback/handler, but forward on an id or key or index.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, thought it was discouraged in general but if there isn't a better way to pass parameters I guess it is the way to go.
1

The alternative is to use .bind but it's not recommended because a new function is created upon each render() call.

updateProgress(arg, event) {
  console.log(arg, event); // Prints: 1 Proxy {dispatchConfig: Object ...
}

render() {
  return
    ...
    <Button onClick={this.updateProgress.bind(this, 1)}>Increase</Button>
}

3 Comments

Isn't this worse still? It binds on every button click, not just on every render? Or am I misunderstanding?
It's correct, it binds on every render. Every button click calls the bound function which is updateProgress
This is basically the same thing; an arrow function creates a new function on each render() call too. The main advantage of the arrow function is that it arguably has cleaner syntax.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.