Code works fine, but I can't figure out how to remove this error in VSCode. Thanks for help.
import * as React from 'react';
interface State {
text: string;
}
export default class Example extends React.Component<State> {
state: State = {
text: 'SOME TEXT'
}
private handleChange = () => {
this.setState({text: 'New Text'}); //error: property setState does not exist on type Example
}
public render(){
return(
<div>
<h2 onClick={this.handleChange}>{this.state.text}</h2>
</div>
)
}
}
First off, make sure you have the react type definitions installed:
npm install @types/react @types/react-dom
Secondly, the generic for state goes second, not first. The first one is for props.
export default class Example extends React.Component<{}, State> {
Look at the React type definitions to verify this (go to definition on Component
). <P, S>
means props, then state.
class Component<P, S> {
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With