getting valueState of react-bootstrap-switch

- 1 answer

Ad

I am using react-bootstrap-switch in react app I am building and am having trouble getting the state of the switch.

This is how I render the switch:

<Switch value={'off'} state={this.state.storyStatus} size={'small'} onColor={'danger'} onChange={this.handleChange}/>

I have used this for the change handler:

handleChange: function () {
      console.log(this.state);
      //this.setState({storyStatus: !this.state});
  },

and this is my initial state method:

getInitialState: function() {
    return {
        storyStatus: "false"
    };
  },

the console.log simply logs the initial state, not the actual state of the switch.

Using the react developer tools I can see the state changing when I operate the switch, but cannot seem to pull value of the switch state.

enter image description here

Ultimately i would like to change the background colour of an li element based on the state of the switch.

Ad

Answer

Ad

Note that handleChange is defined on the parent component, which renders your Switch component. That's why this.state refers to the state of this parent component, not the state of your Switch component.

In the same way, getInitialState defines the initial state of the parent component, where the only thing we define is storyStatus: "false".

To read the value from the Switch component, the onChange callback gives you access to the component and state (source).

So doing

handleChange(component, state) {
  console.log(state);
}

should do the trick.

Ad
source: stackoverflow.com
Ad