Home > Software design >  How to call different function on each click on the same button in react
How to call different function on each click on the same button in react

Time:10-08

we have a button and have to call different function it is being clicked. Please suggest some ways in react

 const handleClick= ()=>{
 // on first click call func1
func1();
// on second click call func2
 func2();
 // on third click call func3
 func3();
 }


 <button onClick ={()=>{handleClick()}}>Call diff function </button>

CodePudding user response:

First set up the state for component:

const [clickCount, setClickCount] = useState(0)

Define your handleClick function with a switch case that updates the state of the click count for each case:

const handleClick= () => {

switch(clickCount) {
  case 0:
    /* Call function 1 */
    setClickCount(1)
    break;
  case 1:
     /* Call function 2 */
    setClickCount(2)
    break;
  case 2:
     /* Call function 3 
        you can then reset the state to the 0 if you wanted */
     setClickCount(0)

    break;
  }
}

Then set up your button to call the click like so:

<button onClick ={()=>{handleClick()}}>Button</button>

CodePudding user response:

Have a state called count. At each click increase the count and by checking the count and call different functions.

 const [count, setCount] = useState(0);

  const handleClick = (event) => {
    if (count == 0) {
      console.log("first");
    } else if (count == 1) {
      console.log("second");
    } else if (count == 2) {
      console.log("third");
    }
    setCount(count   1);
  };
  • Related