Garmaine Staff asked 2 years ago

In my react app, I'm trying to achieve the results of toggling background colors of a graph, even if a graph is already loaded/rendered on screen.

With my current code, if I click the checkbox to toggle the colors it works perfectly fine as far as setting the colors in state and passing those into my component, but I have to reload the component on screen to see the changes, but they do show at that point.

I've tried to use forceUpdate() to rectify this but to no avail

What should I do at this point to make sure that when the state changes in this function it reloads the component completely?

state = {
  renderCalories: true,
  graphBackgroundColor: '#fff',
  graphLabelColor: '#000'

};


toggleCOlor = event => {
  console.log('toggling color');
  this.setState({
   graphBackgroundColor: '#000',
   graphLabelColor: '#fff'
  });
 this.forceUpdate();
}
render() {
 return (
  <div>
   <div className={styles.dropDown}>
     <FormControl style={{minWidth: 120}} className={styles.formControl}>
      <FormControlLabel
        value="end"
        control={<Checkbox color="primary" />}
        label="Toggle Graph Background Color"
        labelPlacement="end"
        onChange={this.toggleCOlor}
      />
      </FormControl>
    </div>

  {this.state.renderCalories && <NetCalorieTrend backgroundColor={this.state.graphBackgroundColor} labelColor={this.state.graphLabelColor} />}

...
}