Last updated: Apr 7, 2024
Reading time·2 min
To call multiple functions onClick in React:
onClick
prop on the element.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> ); }
We set the onClick
prop on the button, so every time it is clicked, the
supplied event handler function gets invoked.
<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.
An alternative and more readable approach is to extract the event handler function outside of your JSX code.
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> ); }
Every time the button is clicked, the handleClick
function gets invoked and
gets passed the event
object.
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.
<button onClick={handleClick}>Click</button>
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.