This content originally appeared on CodeSource.io and was authored by Pandu Rijal Pasa
If you get cannot read property setState of undefined
when writing a code in React, this article will fix your problem.
The issue occurs because the this
keyword is not pointing out the right scope of the component. You can fix this by binding your function:
constructor(props) {
super(props);
state = {};
this.myFunction = this.myFunction.bind(this);
}
myFunction() {
// your function here
}
Or in the latest (and simple) version, you can use arrow function to avoid binding things. Here is the example:
constructor(props) {
super(props);
state = {};
}
myFunction = () => {
// your function here
}
The post Fix – cannot read property setState of undefined appeared first on CodeSource.io.
This content originally appeared on CodeSource.io and was authored by Pandu Rijal Pasa

Pandu Rijal Pasa | Sciencx (2021-02-20T07:46:26+00:00) Fix – cannot read property setState of undefined. Retrieved from https://www.scien.cx/2021/02/20/fix-cannot-read-property-setstate-of-undefined/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.