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;
To type the useState hook as an object in React, use the hook's generic, e.g. const [employee, setEmployee] = useState<{name: string; salary: number}>({name: '',salary: 0}) . The state variable will only accept key-value pairs of the specified type.
The setState() MethodState can be updated in response to event handlers, server responses, or prop changes. This is done using the setState() method. The setState() method enqueues all of the updates made to the component state and instructs React to re-render the component and its children with the updated state.
It is safe to call setState with a function multiple times. Updates will be queued and later executed in the order they were called.
render() Calling setState() here makes it possible for a component to produce infinite loops. The render() function should be pure, meaning that it does not modify a component's state. It returns the same result each time it's invoked, and it does not directly interact with the browser.
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} />
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