React TypeScript 4.9.5 => onChange typesafe error in React Bootstrap FormControl

71 Views Asked by At

I'm getting the error "Type '(event: React.ChangeEvent<HTMLSelectElement | HTMLInputElement>) => void' is not assignable to type 'ChangeEventHandler<FormControlElement>'." in the following code on the onChange() attribute in "Form.Control" tag.

It is a simple code to update useState hook on change event. I have two elements, an input(FormControl) and a Select(FormSelect). It works as intended when I create an individual onChange() method for both of them but when I use Union( | ) for "HTMLSelectElement" and "HTMLInputElement" in a single method as shown below it throws the error.

const handleChange = (
    event: React.ChangeEvent<HTMLSelectElement | HTMLInputElement>
  ) => {
    const { name, value } = event.target;
    setUsers({ ...users, [name]: value });
    console.log(users);
  };

  return (
    <div>
      <Form onSubmit={handleSubmit}>
        <Form.Group className='mb-3' controlId='formBasicName'>
          <Form.Label>Name</Form.Label>
          <Form.Control
            onChange={handleChange}
            value={users?.name}
            name='name'
            id='name'
            type='text'
            placeholder='Name'
          />
       </Form.Group>
       <Form.Group className='mb-3' controlId='formBasicRole'>
          <Form.Select
            aria-label='Select Role'
            onChange={handleChange}
            value={users?.role}
            name='role'
          >
            <option>Select</option>
            <option value='Admin'>Admin</option>
            <option value='User'>User</option>
          </Form.Select>
        </Form.Group>
      </Form>
    </div>
  );
};

Now if I remove the "HTMLSelectElement |" from the parameter, the onChange() in "Form.Control" tag will start working fine but as expected, the one in "Form.Select" will throw an error. I also tried changing the "Form.Control" to simple "input" tag and also creating separate methods after which it works just fine but I still wonder why it doesn't work when I use a Union( | ).

0

There are 0 best solutions below