React: What is ‘this’ and why am I getting this Error?
If you are unfamiliar with Class-based components you are bound to come across this error:
You’ll look back at your code for minutes and see nothing wrong. You’ll keep asking yourself why is ‘props’ (or ‘state’) undefined!? I am clearly passing information to it!!!
This stems from how the keyword ‘this’ operates. To start, ‘this’ is a reference to the Class itself. When you are writing this.functionName
it is essentially the same thing as className.functionName
. Or if you are using state it would be this.state.stateKey
.
The issue lies in where you invoke the keyword ‘this’. The image above is a Class function for submitting a form. This is the exact function that led to the error at the top. The easy explanation for this error is that when this.props
is called within the function, it is calling ‘this’ only inside the function and not referencing the class, essentially stripping the function from the class.
There are two solutions to this problem:
- If you want, you can use a constructor and add the code below. This will bind the function to the Class that way ‘props’ will be recognized from the Class and not the function. But I only suggest using this method if you are already using constructor + super.
2. The other way is simple. Just convert your functions into arrow functions. Arrow functions are the new ES6 way of writing functions and they automatically bind to JavaScript classes.
More content at plainenglish.io