TypeError: Cannot read property ‘setState’ of undefined ReactJS

The issue

This is the issue we got into when we tried to change the state of a class component in ReactJS. We wrote the regular method inside the and inside that method, we were trying to change the state of the component like below:

class SubscriptionList extends React.Component {
    static contextType = AppContext;
    componentDidMount() {
        const appContext = this.context.selectedCampaign;
        this.setState({ data: appContext, isDropdownShown: false});
    }

    toggleProductDropdown () {
        this.setState({isDropdownShown: !this.state.isDropdownShown});
    };

return (
    <div className="w-form" onClick={this.toggleProductDropdown}></div>
)
}

The above code runs well but as soon as we trigger the click it fails and shows this error message:

TypeError: Cannot read property 'setState' of undefined ReactJS 

The solution

The issue happens because the method is not properly bind with this. As we all know that when we create a function it has it’s own special object this.

As the arrow function does not have any special object this. This problem can be solved with the arrow function like below:

class SubscriptionList extends React.Component {
    static contextType = AppContext;
    componentDidMount() {
        const appContext = this.context.selectedCampaign;
        this.setState({ data: appContext, isDropdownShown: false});
    }

    toggleProductDropdown = (event) => {
        this.setState({isDropdownShown: !this.state.isDropdownShown});
    };

return (
    <div className="w-form" onClick={this.toggleProductDropdown}></div>
)
}

Here is a good article about bind of ReactJS component classes.

Here are the StackOverflow answers.