Bill
Bill

Reputation: 5150

React TypeScript: Correct Types for onChange

What are the correct types for target: { value: any, name: any }? The error I get is Duplicate identifier 'any'. I also get the error Binding element 'any' implicitly has an 'any' type. And why does value give the error 'Cannot find name 'value'?'

I have a code sandbox here


const [state, setState] = useState({
    fullName: '',
});

const { fullName } = state;

const onChange = ({ target: { value: any, name: any } }) => {
    setState((prev) => ({
        ...prev,
        [name] : value, // <= 'Cannot find name 'value'
    }));
};

...

<input
  type='text'
  placeholder='Full name'
  name='fullName'
  value={fullName}
  onChange={onChange}
/>

Upvotes: 8

Views: 22279

Answers (1)

svltmccc
svltmccc

Reputation: 1386

event from onChange should be ChangeEvent<HTMLInputElement>

So, you must do this:

const [fullName, setFullName] = useState('');

...

const onChange = (event: ChangeEvent<HTMLInputElement>) => {
    setFullName(event.currentTarget.value);
};

...

<input
  type='text'
  placeholder='Full name'
  name='fullName'
  value={fullName}
  onChange={onChange}
/>

Upvotes: 18

Related Questions