Random Color Picker button background color

Hi all,

Just a quick question on this project: I haven’t been able to understand why the background color of the button is also changing with every single click on the Refresh button…

Does anybody know why this is the case?

First in Random.js there is this function (isLight) which determines if the background-color is light. If we have a light color then the RGB values will be higher. White is 255,255,255 or #FFFFFF. It is adding up the 3 RGB values from the color array and checking if they are less than 127 * 3 (which is approximately half of 255 * 3). The name reduce is a little confusing for that array method as it can be used for a ton of stuff, including adding numbers.

To me it seems like the isLight function will return true for a dark color (which means it is named a little strangely - perhaps isDark would have been better). But either way it returns true or false depending on the lightness/darkness of the background-color stored in state.

  isLight() {
    const rgb = this.state.color;
    return rgb.reduce((a,b) => a+b) < 127 * 3;
  }

Then in Button.js the class-name of the button is changed depending on if the light prop is true and the button’s class is set to either ‘light-button’ or ‘dark-button’. Here it seems a little strange that light-button class is set if the light prop is set to true. But I think that this may cancel out the unexpected output from the isLight function.

<button 
	className={ this.props.light ? 'light-button' : 'dark-button' }
        onClick={this.props.onClick} >
	Refresh
</button>

Finally, in the css-file there are selectors for both of the button classes which make them either white or black but with an alpha value of 0.5 depending on which class is assigned to the button. The alpha means that the button is 50% transparent so the button will also be tinted by the background-color at the same time as it has the white or black coloring.

.light-button {
  background-color: rgba(255,255,255,0.5);
  color: rgb(0,0,0);
}

.dark-button {
  background-color: rgba(0,0,0,0.5);
  color: rgb(255,255,255);
}

Thanks for the very clear explanation, Mike. Now I understood why the background color of the button is also changing.
I was expecting it to be only white or black, due to the rgb components of the “background-color” key of the “light-button” and the “dark-button” classes in the css file.
But because the alpha parameter is set to 0.5, the final background color of the button is actually a mix between half the background color of the page and half white (or half black).
It all makes sense, in the end! Thanks again!