Reactjs – Property ‘value’ does not exist on type ‘Readonly<{}>‘

reactjstypescript

I need to create a form that will display something based on the return value of an API. I'm working with the following code:

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {value: ''};

    this.handleChange = this.handleChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
  }

  handleChange(event) {
    this.setState({value: event.target.value});
  }

  handleSubmit(event) {
    alert('A name was submitted: ' + this.state.value); //error here
    event.preventDefault();
  }

  render() {
    return (
      <form onSubmit={this.handleSubmit}>
        <label>
          Name:
          <input type="text" value={this.state.value} onChange={this.handleChange} /> // error here
        </label>
        <input type="submit" value="Submit" />
      </form>
    );
  }
}

I'm getting the following error:

error TS2339: Property 'value' does not exist on type 'Readonly<{}>'.

I got this error in the two lines I commented on the code. This code isn't even mine, I got it from the react official site (https://reactjs.org/docs/forms.html), but it isn't working here.

Im using the create-react-app tool.

Best Answer

The Component is defined like so:

interface Component<P = {}, S = {}> extends ComponentLifecycle<P, S> { }

Meaning that the default type for the state (and props) is: {}.
If you want your component to have value in the state then you need to define it like this:

class App extends React.Component<{}, { value: string }> {
    ...
}

Or:

type MyProps = { ... };
type MyState = { value: string };
class App extends React.Component<MyProps, MyState> {
    ...
}