this in React Components?

Parwat Kunwar
Aug 26, 2017 · 2 min read
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} />
);
}
}
  1. this here represents the HelloWorld component 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 error cannot read the property of undefined. But, the state is defined and it have the message property in it.
  2. Probably you may know how to solve this issue, either you will use the bind to switch the context of this or use the => notation in function definition.
  3. Ever Guessed, why you have to that, yes you might have, and the answer is to take the HelloWorld component context, But shouldn’t bethis auto-taking the component context. Nope, it doesn’t! But why?

And this article is about that

But shouldn’t be this auto-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 it always 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.

)

Parwat Kunwar

Written by

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade