Tell us what’s happening:
I don’t have a problem with the challenge itself, but I don’t really understand what’s going on. I understand that we bind ‘this’ to the ‘handleClick’ method so that it has access to ‘this’, but then why don’t we bind ‘this’ to the ‘render’ method? If handleClick doesn’t work without binding ‘this’, then why does render?
Challenge: React - Bind ‘this’ to a Class Method
Link to the challenge:
Welcome to the community!
reactjs - bind(this) in ReactComponent.render() method - Stack Overflow
bind this in the render method. Binding
this in the render method will cause React to create a new function every time your Component is rerendered. This is why we most commonly bind in the constructor.
Thanks for the reply,
I don’t think I’ve described my problem well enough.
I am not asking why we don’t bind this IN the render method, I’m asking why we don’t bind this TO the render method i.e. why don’t we do the following:
this.render = this.render.bind(this)
render is a method, just like
handleClick, so I don’t understand why we only bind
Sorry about that. Maybe somebody else can provide a different response.
I think of them as the same result being the reason. But, I do not know even half of it. lol
Keep up your good progress!
handleClick is finally executed when you click on the button it won’t have a
this because it is not being called on an object of the class but rather as a stand alone function. So unless you bind it to the
this of the class then it won’t have one.
You can see this for yourself by adding
console.log(this); as the first line of
handleClick(). When you bind
this to the method and click the button then you will see the
this object for the class in the console pane. But if you comment out the line in the constructor that binds
this to the method then you will see
undefined in the console pane when you click the button. (You’ll also see a TypeError, but you can ignore that.)
render method on the other hand is never called as a stand alone function. It is always called on an object of the class, so you don’t need to bind it to
this. You can if you want to, but it won’t gain you anything.
Update: Ahh, I didn’t quite read your question correctly. I see that you already understood the stuff in my first two paragraphs and you only needed my explanation in the third paragraph. My bad.