Call Multiple Functions onClick in React
Dev Samay
Senior ReactJS Developer

Creating interactive user interfaces in React often involves managing events like onClick. These events can trigger various actions or functions in yo...
Creating interactive user interfaces in React often involves managing events like onClick. These events can trigger various actions or functions in your application. When it comes to handling multiple functions on a single event, such as a button click, there exist several approaches to achieve this goal. This article will explore two different methods for Call multiple functions onClick in React.
Method: 1 Using Function Composition
Here’s a simple technique for calling multiple functions when a button is clicked in React. We achieve this by using a Function Composition. This method entails creating a new function right where it’s needed, which then calls the functions you want to execute.
1import React from 'react';
2function App() {
3 const handleClick = () => {
4 function1();
5 function2();
6 };
7 const function1 = () => {
8 console.log('Function 1 is executed');
9 };
10 const function2 = () => {
11 console.log('Function 2 is executed');
12 };
13 return (
14 <div>
15 <button onClick={handleClick}>Click Me</button>
16 </div>
17 );
18}
19export default App;In this code snippet, handleClick is the main function responsible for triggering both function1 and function2 upon a button-click event. This method is particularly handy for smaller projects or when you prefer to keep your code structure clear.
Method: 2 Inline Arrow Function
We can also call multiple functions directly within the onClick the event handler, using an inline arrow function.
1import React from 'react';
2export default function App() {
3 const function1 = () => {
4 console.log('Function 1 called');
5 };
6 const function2 = () => {
7 console.log('Function 2 called');
8 };
9 return (
10 <div>
11 <button
12 onClick={event => {
13 function1();
14 function2();
15 }}
16 >
17 Click
18 </button>
19 </div>
20 );
21}Conclusion
Calling multiple functions onClick in React can be achieved using various approaches. we can choose the method that best fits your specific use case and coding style. Whether it’s using inline arrow functions or function composition, React provides flexibility to handle events in a way that suits our application’s needs. Remember to select the approach that aligns with the complexity of our application and our coding preferences. With these techniques, we can efficiently handle multiple function calls in your React components.
You may also like:
About Dev Samay
Senior ReactJS Developer with extensive experience in building scalable web applications. Passionate about modern JavaScript frameworks, best practices, and creating exceptional user experiences.