In JavaScript, this
is what’s referred to as the calling context. It’s the object some thing (some property, be it a value or a function etc) belongs to.
So in the class, where you’ve written this.state.name
, that’s the property name
, which belongs to the object state
, which belongs to the object created by the MyApp
class. There isn’t any need to bind anything.
The complication with JavaScript is that every function creates its own calling context. If you define a normal function (or method you would say here, a function attached to the MyApp
class) –
class MyApp extends React.Component {
constructor(props) {
super(props);
this.state = {
name: 'CamperBot'
}
}
printName() {
return this.state.name;
}
render() {
return (
<div>
<Navbar nameFn={this.printName}/>
</div>
);
}
}
Well, now there is a problem, because when you try to call that function in Navbar
, it isn’t going to return CamperBot
. this
is not going to refer to the object created by MyApp
, it’s going to refer to the object created by Navbar
. And unless Navbar
also has a state
object with a name
property, it isn’t going to work.
So that is when you need to bind things – when you pass a function that uses this
into another calling context. What bind
does is wrap the function in another function that keeps hold of the original this
context. With a static value it doesn’t matter – it’s a value that goes straight into the child component’s props
.
So:
- if you’re using a class, and
- if you are defining normal methods*…
- that refer to
this
, and
- you want to pass those methods to a child component
Then you’ll need to bind them in the constructor – it’s a single, quite ugly looking line for each one, like so:
class MyApp extends React.Component {
constructor(props) {
super(props);
this.state = {
name: 'CamperBot'
}
this.printName = this.printName.bind(this);
}
printName() {
return this.state.name;
}
render() {
return (
<div>
<Navbar nameFn={this.printName}/>
</div>
);
}
}
Sorry if this seems a little like gibberish, it’s a painful bit of JavaScript for a lot of people learning the language. For some reading and some practice, I’d Google for explanations of this
, you might need to go through quite a few until you get an explanation that makes the most sense (I remember it taking a long while until it fully clicked for me)
* you can avoid needing to bind by using arrow functions, which is nicer to read and write, but I’ll not complicate things further.