How to insert 2 functions into onClick event ReactJS?

Viewed 23
<Button onClick={submitHandler}>

I have this button which already has an assigned function to its onClick event. I also want to add <Button onClick={() => Toggle()}> this Toggle function into same button. How can I do it?

3 Answers

Simply create a function which calls both of the functions. Assuming submitHandler needs the event object, that will look like:

<Button onClick={(event) => {
  submitHandler(event);
  Toggle();
})}>

if you want to handle event you need to do onClick={(e) => { submitHandler(e); Toggle(); }.

if you don't want to handle event just do onClick={() => { submitHandler(); Toggle(); }.

First, think of separating your functions you can do something like :

<Button onClick={(e) => handleClick}>

And then create your functions which gonna look like:

const handleClick = (e) => { handleSubmit(e); handleToggle();}

You can later work on each function apart:

const handleSubmit() => { // your code  }
const handleToggle() => { // your code  } 
Related