Click is one of the most common events in React. In this article, you will learn how to create an advanced function to handle clicks and pass additional parameters to onClick event handlers in React.

Pass Parameters to onClick in React

React developers set onClick to a function to be executed when click event occurs. This function is an event handler. In React, element’s onClick attribute is set to a function definition.

You can call normal JavaScript functions and pass them as many parameters as needed. Event handlers are called when a certain event occurs, so you can’t easily pass parameters to them.

But how do you pass parameters to onClick function in React?

First, let’s understand what happens when user clicks a button.

When called, onClick event handler receives one parameter by default – an instance of SyntheticEvent. First argument in the function definition of event handler is a stand-in for SyntheticEvent. React developers often use event or e for short.

An easy solution is to create an extra function to call in the event handler.

User clicks the button -> onClick event handler executes -> onClick calls another function.

The inner function can accept as many arguments as you need.

Code example

Let’s look at an example:

In this code, handleClick function can accept as many parameters as needed.

The purpose of onClick is to call our main function handleClick. Whenever user clicks a button, handleClick executes as well. In essence, we are indirectly passing a parameter to onClick function in React.

<button> element’s onClick attribute is set to a function (1) that calls handleClick function (2).

Why pass parameter to onClick function?

You may need to pass a parameter to onClick for a number of reasons. First of all, it can help you reuse code. One onClick event handler that accepts multiple arguments can be reused in different ways throughout your app.

For example, passing a parameter to onClick can help you reuse one function to handle multiple buttons, instead of having to create a separate handler for each one.