Q:

React - add and remove from state with checkbox

I have a demo here
It's a simple React app with a checkbox.
I'd like to add something to state when the checkbox is selected and then remove it from the state when it's unselected.
I have it working when it's selected but how do I remove it from the state when unselected.
handleChange = (e) => {
const array = [...this.state.colors];
const index = array.indexOf(e.target.name)
if (index !== -1) {
  this.setState({colors: this.state.colors.filter(() => {
    color !== e.target.name
  })})
}else{
  this.setState({colors: e.target.name})
}

}

A:

You can access the state of a checkbox with event.target.checked.
Previous state can be accessed with callback version of setState
Docs

handleChange = (e) => {
    const checked = e.target.checked;
    const selectedColor = e.target.name;
    if(checked) {
      this.setState(prevState => ({
        colors: [...prevState.colors, selectedColor]
      }));
    } else {
      this.setState(prevState => ({
        colors: prevState.colors.filter(color => color!==selectedColor)
      }));
    }
  }

Stackblitz

