This Bindings in React Components

In React, when passing arguments to other components the ‘this’ binding becomes important.

Checkout this code snippet that I’ll use to demonstrate examples of when to use the this binding in React components:

In the below code snippet, line 28 creates a VideoList component and passes in arguments: refreshVideo and videos, in order to create the component.

When passing refreshVideo, since it makes reference to this.setState within the function, we must bind this. Otherwise without it,

if we simply passed in this.refreshVideo, it would pass in the function but the this.setState would be empty since it has no reference to this. In VideoList component, this will refer to the component itself. So in VideoList when we call the function it will run right there as a standalone function and it will see this.state and it will refer to the component and see if the component has .state which it doesn’t. Thus we need to change the this in the function, and make sure that it always refers to the this that was intended in the original function before passing it as an argument (this.setState) which should be referring to the App Component not the VideoList component. Therefore we need to bind this like this (love the pun lol): this.refreshVideo.bind(this)

Note that videos does not do a bind. It’s just this.state.videos. The reason for that is simply because this.state.videos is an object (see line 6) which does not make any references to the App component via this. If it did (for eg. videos: {vid: this.state}) then we

would have to do a binding like this.state.videos.bind(this)

Hope that makes sense!