Random Color Picker

Hi guys, if you have already done the Random Color Picker project, I got a question for you.

In this exercise, the only function that we bind is the handleClick function because It uses ‘this’. But as others functions in the same exercise use ‘this’ (for example isLight), why aren’t they binded ?


If you have an answer, It would be cool to explain It to me. Thank you ! :smiley:

1 Like

Only one of the instances of ‘this’ is necessary to bind to the class method Random because it is the only one where it is referenced outside of the Random method.
We have the Button component in Button.js that needs to use an instance of ‘this’ that is not referring to itself, but to the Random method.

Here is my take on what is happening:
There is an instance of ‘Button’ that is called in the render() method of Random.
It has 2 attributes that are passed along with the call to Button.

The first is light, which has a true or false value from the isLight() function.
For this attribute, the isLight function is called, and the value (true or false) is what is passed along as a prop to Button.

The second is onClick which is sending a function, rather than a value. The function includes the term ‘this’ in it. It is passed to Button, so it becomes a prop of Button. It will be called in Button, and the component will confuse it as wanting to call a method of Button that doesn’t exist. So, by binding the ‘this’ in the instance of using ‘this.handleClick’ function. the function is always bound to the ‘Random’ component as it’s parent rather than any other component.

And, of course, any of the other instances of ‘this’ (apart from this.handleClick) are not used outside of Random. So, they will always point to the correct parent component of Random where those functinos exist.

I hope I got all of this correct. I struggled with this as well. If anyone sees a mistake in my logic, please correct me.
I hope this helps.

1 Like