Call multiple functions onClick in React

avatar
Borislav Hadzhiev

Last updated: Apr 7, 2024
2 min

banner

# 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

The code for this article is available on GitHub

We set the onClick prop on the button, so every time it is clicked, the supplied 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>

The event handler function takes the event object as a parameter and calls the sum() and multiply() functions.

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

# Extracting the event handler outside your JSX code

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

The code for this article is available on GitHub

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

App.js
const handleClick = event => { console.log(event.target); console.log('function 1:', sum(5, 5)); console.log('function 2:', multiply(5, 5)); };

We can call as many other functions as necessary in the handleClick function.

If any of the functions need to take the event object as a parameter, make sure to forward it in the call.

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

App.js
<button onClick={handleClick}>Click</button>
The code for this article is available on GitHub

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.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.