1

In my react application the background-color for some child elements is given through props from state. Initial value for all colors is null, so the elements are just transparent. After some interaction and clicking user can change the state values to some other colors so the background changes.

After that I want to be able to set all colors back to null but somehow it doesn't work, here is a small part of my code:

 state = { colors: [
              { id: 1, color: null },
              { id: 2, color: null },
              { id: 3, color: null },
              { id: 4, color: null }
                 ]}
 reset = () => {
                let colors = [...this.state.colors]
                colors.forEach(color => color.color = null)
                this.setState({ colors: colors })
                }                        

The values of the color keys in the state change back to null as expected, but the colors of the elements don't disappear. If I try to do something like

 colors.forEach(color => color.color = "red")

then all the colors actually do change to red, but why can't I get the same result with null?

MichaelK
  • 31
  • 4
  • Try [`transparent` instead of `null`](https://stackoverflow.com/questions/8739665/is-background-colornone-valid-css), perhaps by using a class instead of hardcoding the color. – Andy Dec 25 '18 at 23:52
  • 1
    can you share where you're actually setting the background-color? – tobenna Dec 25 '18 at 23:55
  • [Something like this](https://jsfiddle.net/snjz13dr/). – Andy Dec 26 '18 at 00:12

1 Answers1

0

Using transparent instead of null works. Here's a demo

class Colors extends React.Component {
  
  constructor(props) {
    super(props);
    this.state = { colors: props.colors };
    this.reset = this.reset.bind(this);
  }
  
  reset() {
    const colors = this.state.colors.map(({ id }) => {
      return { id, color: 'transparent' }
    });
    this.setState({ colors });
  }  
 
 render() {
    const colors = this.state.colors;
    return (
      <div>
      {colors.map(({id, color}, i) => {
        return <div key={i} style={{backgroundColor: color}}>{i}</div>
      })}        
      <button onClick={this.reset}>Reset</button>
      </div>
    );
  }
}

const colors = [
  { id: 1, color: 'red' },
  { id: 2, color: 'blue' },
  { id: 3, color: 'green' }
];

ReactDOM.render(
  <Colors colors={colors} />,
  document.getElementById('container')
);
div {
  height: 20px;
  width: 20px;
  color: black;
  margin-bottom: 2px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="container"></div>
Andy
  • 61,948
  • 13
  • 68
  • 95
  • Hey it actually works with "transparent", don't know why it didn't work the first time I tried it. Thank you very much. – MichaelK Dec 26 '18 at 00:35