React – How to fix: “Cannot read properties of undefined (reading ‘setState’)”

React

React lets you build user interfaces out of individual pieces called components. Create your own React components like Thumbnail, LikeButton, and Video. Then combine them into entire screens, pages, and apps.

How to reproduce it


import { Component } from 'react';

export class StateDemo extends Component {

    state = { title: "Class component", subTitle: "State demo" };

    changeTitle() {
        this.setState({ title: "JavaScript class component" });
    }

    render() {
        return (
            <>
                <h1>{this.state.title} - {this.state.subTitle}</h1>
                <button onClick={this.changeTitle}>Change title</button>
            </>
        );
    }
}

Error

Cannot read properties of undefined (reading ‘setState’)

Solution

Use an arrow function instead of a function.

import { Component } from 'react';

export class StateDemo extends Component {

    state = { title: "Class component", subTitle: "State demo" };

    // use arrow function
    changeTitle = () => {
        this.setState({ title: "JavaScript class component" });
    }
    render() {
        return (
            <>
                <h1>{this.state.title} - {this.state.subTitle}</h1>
                <button onClick={this.changeTitle}>Change title</button>
            </>
        );
    }
}
https://www.mldgroup.com

Vyštudovaný top manažér pôsobiaci najmä ako manažér, marketér, softvérový inžinier, konzultant, bloger, YouTuber a zatiaľ neúspešný hudobník a producent. V rámci praxe pôsobil v rôznych odvetviach na rôznych pozíciách v malých aj veľkých firmách, vrátane spoluprác a partnerstiev s významnými firmami či poradenskými spoločnosťami.

Pridaj komentár

Vaša e-mailová adresa nebude zverejnená. Vyžadované polia sú označené *