Call multiple functions onClick in React

avatar

Borislav Hadzhiev

Last updated: May 2, 2022

banner

Check out my new book

Call multiple functions onClick in React #

To call multiple functions onClick in React:

  1. Set the onClick prop on the element.
  2. Call the other functions in the event handler function.
  3. The event handler function can call as many other functions as necessary.
App.js
export default function App() { const sum = (a, b) => { return a + b; }; const multiply = (a, b) => { return a * b; }; return ( <div> <button onClick={event => { console.log('function 1:', sum(5, 5)); console.log('function 2:', multiply(5, 5)); }} > Click </button> </div> ); }

call multiple functions onclick

We set the onClick prop on the button, so every time it is clicked, the provided event handler function gets invoked.

App.js
<button onClick={event => { console.log('function 1:', sum(5, 5)); console.log('function 2:', multiply(5, 5)); }} > Click </button>

In our event handler function, we take the event object as a parameter even though it's not needed in this case and call the sum() and multiply() functions.

You can use this approach to call as many functions in a single event handler as necessary.

An alternative and more readable approach is to extract the event handler function outside of your JSX code.

App.js
export default function App() { const sum = (a, b) => { return a + b; }; const multiply = (a, b) => { return a * b; }; const handleClick = event => { console.log(event.target); console.log('function 1:', sum(5, 5)); console.log('function 2:', multiply(5, 5)); }; return ( <div> <button onClick={handleClick}>Click</button> </div> ); }

onclick multiple functions single event handler

Every time the button is clicked, the handleClick function gets invoked and it gets passed the event object.

In our handleClick function we can call as many other functions as necessary and forward them the event object if they need access to it.

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

If you pass the result of calling the handleClick function to the onClick prop, e.g. onClick={handleClick()}, the function would get invoked immediately when the page loads, which is not what we want.

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