Hello, everyone.
My question doesn’t really have anything to do with the lesson itself, but rather with this particular line of code:
this.handleClick = this.handleClick.bind(this);
As far as my knowledge about this
goes, there are some situations where the value of this
is lost. I do understand what this line of code does(kind of), but i’m trying to understand why this line of code was necessary in this particular scenario. Is it because of this line?
<button onClick={this.handleClick}>Click Me</button>
Does the line above transform behind the scenes into:
document.querySelector('button').addEventListener('click', this.handleClick);
so this
does not reference the React component anymore, but references the button instead? Is this how it is?
**Your code so far**
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
name: 'Initial State'
};
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
// Change code below this line
this.setState({name: 'React Rocks!'});
// Change code above this line
}
render() {
return (
<div>
<button onClick={this.handleClick}>Click Me</button>
<h1>{this.state.name}</h1>
</div>
);
}
};
**Your browser information:**
User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/98.0.4758.80 Safari/537.36 Edg/98.0.1108.43
Challenge: Set State with this.setState
Link to the challenge: