Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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}
/>
like image 454
Bill Avatar asked Jun 10 '26 22:06

Bill


1 Answers

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}
/>
like image 68
svltmccc Avatar answered Jun 12 '26 12:06

svltmccc



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!