2

I'm trying to get this switch https://github.com/pgrimard/react-toggle-switch working in my react project. It is currently working as expected (it toggles and calls the toggleFeature function), however i'm struggling to understand how I would actually link each switch to perform a different action. Normally I would just grab some sort of identifiable attribute in the onClick event to determine which action to carry out, But i'm a bit stuck on how to do it in this case.

Heres my current code (Made it as bare-bones as possible)

class FeatureItem extends React.Component {
  constructor(props) {
        super(props);
        this.state = {on: props.flag};
  }

  _toggleFeature(e) {
    console.log(e); // Undefined
    console.log("ASSD"); // Called on the toggle
  }

  render () {
      <div className="example-usage">
        <p>Switch state: {this.state.on ? 'On' : 'Off'}</p>
         <Switch className= {this.props.description} onClick={this._toggleFeature.bind(this)} on={this.state.on}/>
      </div>
    )
  }
};

Does any one have any idea what i'm doing wrong to get undefined on the event, Aswell as perhaps some idea's on how I can provide my own unique identifier to each button which I could read in the onClick event?

Heres examples of the button: https://github.com/pgrimard/react-toggle-switch/blob/master/example/app/scripts/main.js#L12 if it's any help

Thanks!

1 Answer 1

2

While binding the _toggleFeature function, you can give it arguments with which it will be called:

<Switch className= {this.props.description} onClick={this._toggleFeature.bind(this, 'toggle1')} on={this.state.on1}/>
<Switch className= {this.props.description} onClick={this._toggleFeature.bind(this, 'toggle2')} on={this.state.on2}/>

Now you can differentiate between the toggles in the handler:

_toggleFeature(toggleName) {
  if (toggleName === 'toggle1') {
    // Do some logic for toggle 1
  } else if (toggleName === 'toggle2') {
    // Do some logic for toggle 2
  }
}

Alternatively you can have different handler functions for each toggle, unless you are dynamically creating a variable number of switches.

Sign up to request clarification or add additional context in comments.

1 Comment

I'm dynamically creating them so that works perfectly, Can't believe it was as simple as that second arg :D, Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.