How to pass arguments to onClick event handlers in React

#react #material-ui

Last updated on Jan 3, 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>


Passing 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, which calls the handleClick event handler with an extra argument passed to it.


Example:



const Demo = () => {
  const handleClick(event, status) {
    // add your code here
  }

  return (
    <button onClick={(event)=>handleClick(event, 'active')}>Click Me</button>
  )
}


Passing multiple arguments


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


Example:


const Demo = () => {
  const handleClick1(event, firstName, lastName) {
    // add your code here
  }

  return (
    <button onClick={(event)=>handleClick1(event, 'Suraj', 'Sharma')}>
      Click Me
    </button>
  );
}


Related Solutions



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