How to pass arguments to event handlers in React

Last updated on Jun 6, 2021 by Suraj Sharma



In this tutorial, you’re going to learn how you can pass extra arguments to the event handlers in React


A typical way to call an onClick event handler in a React function component.

<button onClick={handleClick}> Click me </button>

How to pass a single argument


Suppose you want to pass an extra argument along with an event object to the onClick event handler.

You can define an arrow function inside the onClick interpolation, to call the handleClick event handler with an extra argument.

Example:

const handleClick(event, arg1) {
  console.log(arg1)
}

return (
  <button onClick={(event)=>handleClick(event, 'hello')}> Click me </button>
);

How to pass multiple arguments


Similarly, you can pass more than one argument to the onClick event handler.

Example:

const handleClick(event, arg1, arg2) {
  console.log(`${arg1} , ${arg2}`);
}

return (
  <button
    onClick={(event)=>handleClick(event, 'hello', 'world')}
  >
    Click me
  </button>
);


Related Solutions


Rate this post


Suraj Sharma is a Full Stack Software Engineer. He holds a B.Tech degree in Computer Science & Engineering from NIT Rourkela.