0
votes

I am new to React. Here is the problem. when I change the switch state I want to change the theme of whole app.

This is my switch component on the sidebar

constructor() {
    super();
    this.state = { checked: false };
    this.handleChange = this.handleChange.bind(this);
  }

  handleChange(checked) {
    this.setState({ checked });
    console.log('ddd');
  }
  render() {
    return (
      <Switch
        checked={this.state.checked}
        onChange={this.handleChange}
        onColor='#86d3ff'
        onHandleColor='#0061ac'
        handleDiameter={20}
        uncheckedIcon={false}
        checkedIcon={false}
        boxShadow='0px 1px 5px rgba(0, 0, 0, 0.6)'
        activeBoxShadow='0px 0px 1px 10px rgba(0, 0, 0, 0.2)'
        height={10}
        width={30}
        className='react-switch'
        id={this.props.id}
      />
    );
  }

and this is route component that contained by ThemeProvider

<ThemeProvider theme={{ mode: this.state.checked ? 'dark' : 'light' }}>
        ...
      </ThemeProvider>

I want to change the whole app theme when I click on the switch. (Sorry for bad English)

2

2 Answers

0
votes

Can you please try

 handleChange(checked) {
    this.setState({ checked: true });
    console.log('ddd');
  }

As the code here runs on this.state.checked being true or false. Your current code will set the state to be checked:checked instead of checked:true.

If this doesn't help, use React dev tools in your web browser to see what state is doing.

<ThemeProvider theme={{ mode: this.state.checked ? 'dark' : 'light' }}>
        ...
      </ThemeProvider>
0
votes

You can put your component state value to the redux store (or use mobx or react Context) which it can be used by other components.

// switch component
handleChange(checked) {
  this.props.appActions.setAppTheme({ checked }); // this action will set the value to redux store, you should implement the action and reducer method by yourself
}

// other component
<ThemeProvider theme={{ mode: this.props.appState.checked ? 'dark' : 'light' }}>
  // other component connect to the redux store so it can get the state value
</ThemeProvider>