I am doing React: Bind ‘this’ to a Class Method challenge. Here is my code
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
text: "Hello"
};
// change code below this line
this.handleClick = this.handleClick.bind(this)
// change code above this line
}
handleClick() {
this.setState({
text: "You clicked!"
});
}
render() {
return (
<div>
{ /* change code below this line */ }
<button onClick = {this.handleClick}>Click Me</button>
{ /* change code above this line */ }
<h1>{this.state.text}</h1>
</div>
);
}
};
I have two questions.
Q 1) Why do we have to use this.handleClick.bind(this) ? When do we have to use it? Why do we have to do such thing with handleClick but not with state or setState. If I create more methods do I have to bind each method like in such a way?
Q 2) In the line which has this code Click Me. Why doesn’t my code works when I write this.handleClick(). I thought we needed () when calling a function? Is it just with reactjs? When do we use handleClick vs handleClick() ?
Thank you