How to call more than one function within jsx in next.js and react
When coding there are situations in which you need to call multiple javascript functions on button, link or div click. In this post I am going to show you two simple methods to achive this in a next.js or react application.
Method 1
Create another seperate function that calls all the other functions you want. Then call that function you created within jsx as shown below
function First_function(){
console.log("First Function")
}
function Second_function(){
console.log("Second Function")
}
function Third_function(){
First_function();
Second_function();
}
const Page = () => {
return(
<>
<button onClick={Third_function()}>Click me</button>
</>
)
}
From the code above the third functions is called when the button is clicked and this in turn calls the other two functions ( first function and second functions).
This method has the benefit of code reuseability i.e if you are ging to be calling a particular set of functions from diffrent click events then this method is recommend for you.
Method 2
This method is shorter and doesn't involve creating a new function to call the others. All you need to do is to create an array of the functions you wish to call onClick within your website jsx as shown below
function First_function(){
console.log("First Function")
}
function Second_function(){
console.log("Second Function")
}
const Page = () => {
return(
<>
<button onClick={()=>[First_function(), Second_function]}>Click me</button>
</>
)
}
Conclusion
Any of the methods above works and you should use anyone that you feel comfortable with. As always thanks for reading, if you have any questions related to the post then just leave a comment down below and i'll reply you as quickly as I can.