Cannot read property setState of undefined

This will be a very quick guide for the above error.

This is common to have on the react using class or stateful component.

Take the following example


import React, {Component} from 'react';
class App extends Component {
    constructor() {
        super();
        this.state = {name: "default"};
    }

    keyHandler(event) {
        this.setState({name: event.target.value})
    }

    render() {
        return (
            
The name is {this.state.name}
<input id="name" onKeyUp={this.keyHandler} /≶
); } }

if you have something like the above one, where you haven’t bind the method to the class, then the error will happen.

Just adding

this.keyHandler = this.keyHandler.bind(this);

in the constructor will handle the issue.