-2

i have two different function

Deactivate = () => {
 //logic for deactivate
}

Activate = () => {
 //logic for activate
}


   return (
       <div>
          <Toggle
              defaultChecked={this.state.isChecked}
              className="switch-danger"
            />
       </div>
     )

first time click on toggle button when trigger the 'Deactivate function', then second time click trigger 'Activate button'.

benzene
  • 59
  • 1
  • 8
  • 1
    did you visit? https://stackoverflow.com/questions/26069238/call-multiple-functions-onclick-reactjs – bakar_dev Jul 09 '20 at 06:50
  • 2
    `onClick={() => this.state.isChecked ? this.Deactivate() : this.Activate()}` –  Jul 09 '20 at 06:53
  • Do you hold the "activated" value in state to use a simple ternary in a callback handler? Would this be something better suited to a lifecycle function? Can you update your question to include complete code and what, if any, issues you have with what you're trying to do? – Drew Reese Jul 09 '20 at 06:53
  • @DennisVash Not a dupe of that; OP is looking to call either A or B, not both at the same time. –  Jul 09 '20 at 06:58
  • @ChrisG so the dupe with an if on state... – mplungjan Jul 09 '20 at 07:02
  • 2
    @mplungjan Yeah, I guess the method of creating a separate function is close enough; just not sure it's obvious for everybody –  Jul 09 '20 at 07:07

1 Answers1

0

Firstly make Toggle as a controlled component and then if isChecked is true call Activate and false for Deactivate or vice-versa.

...
checkHandler = () => {
  this.setState((previousState) => {
    const isChecked = !previousState.isChecked

    isChecked ? this.activate() : this.deactivate()

    return { isChecked }
  })
}

deactivate = () => {
  //logic for deactivate
}

activate = () => {
  //logic for activate
}

render() {
  const { isChecked } = this.state

  return (
    <div>
      <Toggle
        className="switch-danger"
        value={isChecked}
        onChange={this.checkHandler}
      />
    </div>
  )
}
Aurel Dodon
  • 76
  • 1
  • 4