Pass event and parameter onClick in React


Borislav Hadzhiev

Mon May 02 20221 min read


Photo by SGC

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.
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.

<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.

Use the search field on my Home Page to filter through my more than 1,000 articles.