0

In my react app I have an initial state like this:

state= {
  graphBackgroundColor: '#fff',
  graphLabelColor: '#000',
} 

I have a checkbox that calls this function:

toggleCOlor = event => {
 console.log('toggling color');
  this.setState({
    graphBackgroundColor: '#000',
    graphLabelColor: '#fff',
    renderCalories: event.target.value === 10
  });
}

This works functionally, but no matter whether the ckeckbox is checked or not the colors will now stay what they were set to in that function. How can I make this to toggle so that if the checkbox is checked then graphBackgroundColor is #000 and if it's unchecked it's #fff?

4
  • You have to initialize the state with graphBackgroundColor: '#fff', Commented May 7, 2020 at 3:47
  • what do you mean exactly @Owner? I do have the initial state set as that when the module loads Commented May 7, 2020 at 3:50
  • I think you need to check the check box status. If checked then #fff may be or #000 if not checked Commented May 7, 2020 at 4:02
  • @Tom N. Is there any value assigned to the Key? Commented May 7, 2020 at 4:03

3 Answers 3

2

you can try

     this.setState(prevState => ({
      graphBackgroundColor: prevState.graphBackgroundColor === '#000' ? '#fff' : '#000',
      graphLabelColor: prevState.graphLabelColor === '#fff' ? '#000' : '#fff',
       renderCalories: event.target.value === 10
    }));
Sign up to request clarification or add additional context in comments.

Comments

1
toggleCOlor = event => {
 console.log('toggling color');
  this.setState({
    graphBackgroundColor: this.state.graphBackgroundColor === '#000' ? '#fff' : '#000',
    graphLabelColor: this.state.graphLabelColor === '#fff' ? '#000' : '#fff',
    renderCalories: event.target.value === 10
  });
}

If you want, you can write a function which passes in the current colour and return the toggled colour instead of the one lined ternary operator.

returnAlternateColor = (color) => {
    if(color === "#fff") return '#000;
    if(color === '#000') return '#fff';
}

and then call this function passing this.state.graphLabelColor instead of the ternary operator. This way you can have even more options.

Comments

1

create a function onChange to check or unckeck

onChange=(e)=>{
 [e.target.name]:e.target.value
}

you can create a function for example to change of color:

myStyleWithConditional=()=>{
   background:event.target.value === 10? "#000":"#fff"
}

and in your return

<div style={this.myStyleWithConditional}></div>
<input type="checkbox" name="check" value=10>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.