does_not_compute does_not_compute - 1 year ago 228
React JSX Question

React toggle button issue

I'm trying to get this 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) {
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}/>

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: if it's any help


Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download