Published on

Using Function Closures to Pass Parameters in a Callback in React


The Issue - Using an event handler callback that needs to be passed parameters

While breaking a component apart in React I came across a case where I needed the parent to communicate with the child. This needed to happen when a button was clicked. The problem is that you need to pass a function pointer <button onClick={someFunction}>. As soon as you put parameters into it you invoke it instead of passing it around <button onClick={someFunction(name)}>.

After a bit of research I found that the easiest and simplest way to achieve this is by passing a callback function to the child from the parent. In my case this callback would be used by the button for example:

<button onClick={this.props.onPushedCallback}>Say Hi!</button>

The problem in my case was that I needed the callback to be able to take parameters in from the child and use those parameters but in a function pointer.

Solution - Function Closure

After a bit of searching I found a very nice solution which can also be applied to Javascript in general. You use a closure which takes in the parameters you need and returns a function that can use those parameters. For the sake of illustration assume that I want to pass a person's name and surname from the child to the parent. In the parent I define a callback to handle this as follows:

Parent Component - Setting up and passing the callback

onSayHiClickHandler(name, surname) {
    return () => {
       // do your logic here using the variables from the outer function

Assuming this callback is passed to the child using a prop called onPushedCallback I would pass it as follows:

<ChildComponentIAmUsingInParent onPushedCallback={onSayHiClickHandler} />

Child component - Using the callback as a prop

And finally in the child I use the callback as follows:

<button onClick={this.props.onPushedCallback(name, surname)}>Say Hi!</button>

(Optional) Parent component - Defining a callback that takes parameters and the event in an event handler

This works as the onPushedCallback prop as defined in the parent returns a function with zero parameters, but using a closure that zero parameter function can use whatever values it needs to. As this is being attached to an event handler you can also pass the event as a parameter to the returned function if needed:

onSayHiClickHandler(name, surname) {
    return (event) => {
       // do your logic here using the variables from the outer function
       //use event however you need to here