Theme state changes will be rerendered just once in ThemeProvider

Viewed 488

I am a beginner in ReactJs and I want to change the theme just by clicking a button. But this just works for one time clicking a button, every click after will not have any effect.

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      theme: DarkTheme
    };
  }

  render() {
    return (
      <ThemeProvider theme={this.state.theme}>
        <div className="App">
          <Toolbar>
            <Button
              onClick={() => {
                this.setState({
                  theme: LightTheme
                });
              }}
            >
              <Typography color="primary" variant="body1">
                Light
              </Typography>
            </Button>
            <Button
              onClick={() => {
                this.setState({
                  theme: DarkTheme
                });
              }}
            >
              <Typography color="primary" variant="body1">
                Dark
              </Typography>
            </Button>
          </Toolbar>

          <Typography color="primary" variant="body1">
            Some text here that should always be displayed in primary color of current theme
          </Typography>
        </div>
      </ThemeProvider>
    );
  }
}

CodeSandbox

Can anybody explain what I did wrong?

Using @material-ui/core@v.5.0.0-alpha.8

1 Answers

Perform a copy of your theme object when setting the new state and it should work

onClick={() => {
  this.setState({
    theme: {...LightTheme}
  });
}}
 
Related