-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'.

6
  • 1
    did you visit? stackoverflow.com/questions/26069238/… Commented Jul 9, 2020 at 6:50
  • 2
    onClick={() => this.state.isChecked ? this.Deactivate() : this.Activate()} Commented Jul 9, 2020 at 6: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? Commented Jul 9, 2020 at 6:53
  • @DennisVash Not a dupe of that; OP is looking to call either A or B, not both at the same time. Commented Jul 9, 2020 at 6:58
  • 2
    @mplungjan Yeah, I guess the method of creating a separate function is close enough; just not sure it's obvious for everybody Commented Jul 9, 2020 at 7:07

1 Answer 1

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>
  )
}
Sign up to request clarification or add additional context in comments.

2 Comments

please describe me using code
@benzene check my edit

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.