Pass Arguments To Event Handler Function In React

August 18, 2020 by Andreas Wik

pass arguments to function in onclick event handler in react

Let’s say you have a component with a button. When users click the button a function should run. This could easily be done with:

<button onClick={runAudit}>Audit</button>


This will trigger the runAudit function on click as expected.

But what if you need to pass some arguments to it, like an id? You may be tempted simply do:

<button onClick={runAudit(id)}>Audit</button>


This won’t have the desired effect, though. It will trigger the runAudit function as soon as the component is mounted, and not when the button is clicked.

To get this to work, you’ll need to use an arrow function to run it:

<button onClick={() => runAudit(id)}>Audit</button>


And voila!

The runAudit function runs when the button is clicked and the arguments are passed, just the way we like it.

Recommended reading

Share this article