class MyComponent extends React.Component {
constructor() {
super();
this.state = {
count: 0,
};
}
handleClick() {
this.setState({ count: this.state.count + 1 });
}
render() {
return (
<div>
<h1>Counter: {this.state.count}</h1>
<button onClick={this.handleClick}>Increment</button>
</div>
);
}
}
export default MyComponent;
getting this error:
Error Message: TypeError: Cannot read property ‘count’ of null
anyone who can help me, What is the error in my code.
3
Answers
When you call
handleClick
from the<button />
‘sonClick
event, it loses its reference to the component’s instance, resulting in thethis
keyword pointing tonull
instead of the component instance.By binding
this.handleClick
to the component instance, you make sure that thethis
keyword inside thehandleClick
refers to the component instance, allowing you to accessthis.state.count
(or betterthis.state
) properly.You also could use an arrow function.
The arrow function automatically "captures" the
this
value from the component instance. Because of that, you can accessthis.state.count
(or betterthis.state
) within thehandleClick
function.Need to bind the function/method