this in React Components?
class HelloWorld extends React.Component {
constructor(props) {
super(props);
this.state = { message: 'Hi' };
}
logMessage() {
console.log(this.state.message);
}
render() {
return (
<input type="button" value="Log" onClick={this.logMessage} />
);
}
}thishere represents theHelloWorldcomponent context. So, the upper line of code should work as expected when we click the button. Nope, it won’t work and will through an errorcannot read the property of undefined. But, thestateis defined and it have themessageproperty in it.- Probably you may know how to solve this issue, either you will use the
bindto switch the context ofthisor use the=>notation in function definition. - Ever Guessed, why you have to that, yes you might have, and the answer is to take the
HelloWorldcomponent context, But shouldn’t bethisauto-taking the component context. Nope, it doesn’t! But why?
And this article is about that
But shouldn’t be
thisauto-taking the component context?
/* this is line of code from HelloWorld Component */ <input type="button" value="Log" onClick={this.logMessage} />
that above input tag which is JSX will be compiled to JS below
React.createElement('input', { onChange: this.logMessage, value: "Log" })Remember if
this is used inside an object method italways represents to the closet object.
The below code
{ onChange: this.logMessage, value: "Log" }is same as
{ onChange: this.logMessage() { console.log(this.state.message) } , value: "Log" }// let's assign itlet elephant = { onChange: this.logMessage() { console.log(this.state.message) } , value: "Log" }
consoles undefined, cause this used in console.log inside logMessage() { console.log(this.state.message) } represents the elephant object not the HelloWorld component and there is no state property in it.
So the this used inside the logMessage will be the context of { onChange: this.logMessage, value: "Log" } object which is also declared as elephant object. To solve this issue we have to use bind to take the HelloWorld component context in this, or use => notation in function.
This is mine first article on medium, if there are mistakes, feel free to response
If you enjoyed this article, please help out your friends with a 👏 or a share.
