does_not_compute
does_not_compute

Reputation: 476

React toggle button issue

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!

Upvotes: 2

Views: 2708

Answers (1)

Waiski
Waiski

Reputation: 9680

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.

Upvotes: 2

Related Questions