Pass event and parameter onClick in React

avatar

Borislav Hadzhiev

Last updated: May 2, 2022

banner

Photo from Unsplash

Pass event and parameter onClick in React #

To pass an event and parameter onClick in React:

  1. Pass an inline function to the onClick prop of the element.
  2. The function should take the event object and call handleClick.
  3. Pass the event and parameter to handleClick.
App.js
const App = () => { const handleClick = (event, param) => { console.log(event); console.log(param); }; return ( <div> <button onClick={event => handleClick(event, 'hello world')}> Click </button> </div> ); }; export default App;

react onclick pass event and parameter

We set the onClick prop on the button element to an inline arrow function.

The arrow function takes the event object and calls the handleClick function passing it the event and a parameter.

You can use this approach to pass as many parameters to your event handler functions.

Notice that we are passing a function to the onClick prop and not the result of calling one.

App.js
<button onClick={event => handleClick(event, 'hello world')}> Click </button>

If you invoke the function when passing it to the onClick prop, e.g. onClick={handleClick()}, it would get immediately called when the component mounts.

When a function is passed to the onClick prop, it will only get invoked when the event is triggered an it will always get called with the event object.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.