seState not working
seState not working
In my app component below I want to hide a div based on a function I have defined but it brings an error saying
TypeError: Cannot read property 'setState' of undefined
Please what may be wrong
class Apps extends Component {
constructor(props) {
super(props);
// Don't do this!
this.state = { showing: true };
}
render() {
return (
<div>
<div className="container">
<div style={{ display: (this.state.showing ? 'block' : 'none') }}>
A Single Page web application made with react
</div>
</div>
<div className="buttons">
<a href='' onClick={this.onclick} >Login</a>
<br/>
<a href='' >Signup</a>
<br />
<a href='' >Members</a>
</div>
</div>
);
}
onclick(e){
e.preventDefault();
this.setState({showing: false});
}
}
3 Answers
3
You can e.g. bind the function to this in the render method so that this will be what you expect in your onclick method. You can read more about why this is the case in the documentation.
bind
this
this
onclick
<a href='' onClick={this.onclick.bind(this)}>Login</a>
@AdokiyeIruene If you don't bind it, the value of
this will be the global object which is window in the browser, so it will not work as you want.– Tholle
Jun 30 at 13:27
this
window
You can use bind or you can just use an arrow ES6 function instead of binding it
onclick = (e) => {
e.preventDefault();
this.setState({ showing: false });
}
@Tholle is right. You have to bind your onclick function to current class instance using this. By default this here points to global window obj, which does not have setState function.
Either you bind your function to this, where you are calling it as tholle suggests.
You can also bind it to this in constructor after calling super(props):
this.onclick = this.onclick.bind(this);
this can also be bound implicitly using arrow function like this:
< a href="" onClick={e=>this.onclick(e)} ... ./>
Best practice is to use 2nd option. As using 1st and 3rd options will create new references for the functions each time component renders. However, that's ok to use 1st or 3rd option if you have no problem with memory consumption or creating a small app.
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
If i don't bind it, what will the this be expecting
– Adokiye Iruene
Jun 30 at 13:26