When I do a search on this issue, I can only find questions that modify this.state
directly somewhere in a method body instead of using this.setState()
. My problem is that I want to set a starting state in the constructor as follows:
export default class Square extends React.Component<any, any> {
constructor(props: any) {
super(props);
this.state = {
active: false
};
}
public render() {
...
}
}
The app fails to start with the following compile error:
Cannot assign to 'state' because it is a constant or a read-only property
And this is because in definition of React.Component
we have:
readonly state: null | Readonly<S>;
So I'm not sure how to go about this. The official react tutorial in JS directly assigns to this.state
and says that it is an acceptable pattern to do so in the constructor, but I can't figure out how to do this with TypeScript.