8

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;

2 Answers 2

13

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} />
Sign up to request clarification or add additional context in comments.

Comments

-1

Just do this:

handleChange = (event: Event) => {
      const { value } = event.target as unknown as { value: string, };
      this.setState({
        ...this.state,
        name: value.trim()
      });
};
  
<input type='text' onChange={this.handleChange} />

And the squeegee lines will go away.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.