ReactJS – Parameterized Event Handlers
☞
#reactjs

It is quite frequent requirement to pass parameters to event handlers of custom React components.

There are several ways to achieve this with ES6 depending on weather we need reference to the event or n

We can simply define the event handler and bind it to using JavaScript’s function.

To avoid calling we can use ES6 arrow function which binds the function with automatically

We can also pass additional parameters to event handlers.

To pass parameters to event handlers while using property initializer syntax, we need to use currying.

Provided all the different approaches above, using the arrow function with currying is the most efficient and cleaner way to define event handlers that accepts user defined parameters.

It is quite frequent requirement to pass parameters to event handlers of custom React components. There are several ways to achieve this with ES6 depending on weather we need reference to the event or n @react_devv: ReactJS – Parameterized Event Handlers

☞

#reactjs

It is quite frequent requirement to pass parameters to event handlers of custom React components. There are several ways to achieve this with ES6 depending on weather we need reference to the event or n

function.

If we need to pass custom parameters, then we can simply pass the parameters to the bind call. The SyntheticEvent will be passed as second parameter to the handler.

call function in a JSX prop like above will create a brand new function on every single render. This is bad for performance, as it will result in the garbage collector being invoked way more than is necessary. It may also cause unnecessary re-renders if a brand new function is passed as a prop to a component that uses reference equality check on the prop to determine if it should update.

To avoid creating a brand new function on every single render, we can bind the function in the constructor.

Now, we need not to bind the function while specifying the event handler on line 13.

We can also pass additional parameters to event handlers.

function.

To avoid creating a brand new callback instance on every render, we can use property initializer syntax to correctly bind callbacks.

To pass parameters to event handlers while using property initializer syntax, we need to use currying.

Provided all the different approaches above, using the arrow function with currying is the most efficient and cleaner way to define event handlers that accepts user defined parameters.

I would love to hear your comments, suggestions or questions on above approaches.