7
votes

In this basic example of typescript react (create-react-app) I am trying to change the state.name by a user input.

Could someone show me a working example (which I didn't found) or better: where the documentation is?

The (second) error of the linter is :

(54,24): error TS2322: Type '{ onChange: (e: Event) => void; }' is not assignable to type 'DetailedHTMLProps, HTMLInputElement>'. Type '{ onChange: (e: Event) => void; }' is not assignable to type 'InputHTMLAttributes'. Types of property 'onChange' are incompatible. Type '(e: Event) => void' is not assignable to type 'EventHandler> | undefined'. Type '(e: Event) => void' is not assignable to type 'EventHandler>'. Types of parameters 'e' and 'event' are incompatible. Type 'ChangeEvent' is not assignable to type 'Event'. Property 'cancelBubble' is missing in type 'ChangeEvent'.

import * as React from 'react';
import './Hello.css';

interface Props {
    name: string;
}

interface State {
    name: string;
}

class Hello extends React.Component<Props, State> {

public static defaultProps = {
    name: 'John',
};

constructor(props: Props) {
    super(props);
    this.state = {
        name: props.name,
    };
    this.handleChange = this.handleChange.bind(this);
}

handleChange(e: Event): void {
    this.setState({
        name: e.target.value //Error : property 'value' does not exist on type 'EventTarget'
    });
}

render(): JSX.Element {
    return (
        <div className="hello">
            Hello {this.state.name}
            <input onChange={(e: Event) => this.handleChange(e)} /> //error is at this line
        </div>
      );
   }
}

export default Hello;
1

1 Answers

8
votes

Change your

handleChange(e: Event)

with

handleChange (e: React.FormEvent<HTMLInputElement>)

and

e.target.name;

with

e.currentTarget.name;

Also, you may want to change

 <input onChange={(e: Event) => this.handleChange(e)} />

with

 <input onChange={this.handleChange} />