The issue Cannot read the property of undefined is quite common in JavaScript. When the variable is not defined, JavaScript can not read the undefined variable or property. A similar issue we can find in React JS. We analyze the issue and try to find a solution.
Solution
The issue here is not we what expect i.e. ‘Cannot read property ‘state’ of undefined’, There are 3 approaches in context binding in react.
handlechange() { const course = { …this.state.course, title: event.target.value }; this.setState({ course });}
Approach 1: Bind ‘this
‘ context to own instance – Less preferred
This works, because now this context bound to our class context, i.e {this.handlechange.bind(this)}
to the onChange
event, but It will cause to create an in-function unnecessarily on each render…
Approach 2 : Binding in the Constructor – Less preferred than Arrow function
The most common approach will be to do it in the constructor
because it runs only once, now the function is bound only once, this is called context-binding in the constructor, this approach is preferable, won’t be reallocated on each render
performance wise it is better to bind in the constructor. The bind in constructor method will create a single instance of the function and re-use it, even if the render method is called multiple times
Approach 3: Arrow functions – More preferred
Inherit the binding context of their enclosing scope. basically, they don’t have ‘this’ binding, ‘this’ keyword inside references the class instance.
Tip: How the Arrow function preferred in react state to achieve context binding?
Arrow functions are great. They do look nicer, But there is a much better reason to use arrow functions. It would be more efficient if we know, when and where you are using it.
handlechange = (event) => { const course = { ...this.state.course, title: event.target.value }; this.setState({ course }); };
In above case, the arrow function does not recreate function on each render, Similar to how binding in the constructor works in 2nd approach.