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>
</>
);
}
}