1

how can I specify the event type for radio buttons with ReactJs and typescript

I tried this but it doesn't works for radio buttons though it works for input type="text"

const handleChange = (event: React.ChangeEvent<HTMLInputElement>) => {
   ....    
};
<FormControlLabel
 value="radio1"
 control={<Radio />}
 label=" radio1"
 onChange={handleChange}
/>
<FormControlLabel
 value="radio2"
 control={<Radio />}
 label="radio2"
 onChange={handleChange}
/>

Error

Type '(event: React.ChangeEvent<HTMLInputElement>) => void' is not assignable to type '(event: ChangeEvent<{}>, checked: boolean) => void'.
  Types of parameters 'event' and 'event' are incompatible.
    Type 'ChangeEvent<{}>' is not assignable to type 'ChangeEvent<HTMLInputElement>'.
      Type '{}' is missing the following properties from type 'HTMLInputElement': accept, align, alt, autocomplete, and 329 more.ts(2322)
Satyam Saurabh
  • 488
  • 4
  • 16
  • [this answer](https://stackoverflow.com/a/42645711/547020) implies that `React.FormEvent` should be used (instead of `React.ChangeEvent`) – Eliran Malka Nov 12 '21 at 15:52
  • this isn't working either – Satyam Saurabh Nov 13 '21 at 06:36
  • after reading more, it looks like `currentTarget` is preferred over `target` in most implementations. it's meant to deal with state updates, but here's the interesting part: it seems that a text input is the only element that can accept `target` with no special issues - which is probably related to the issues you're having on the typescript build - it has a separate interface altogether. i would look into what differs this interface from other form controls, i'm sure you'll find some hints there on how to solve this – Eliran Malka Nov 13 '21 at 21:21

2 Answers2

0

Thanks, Any way I found the solution. <HTMLInputElement> is not assignable to radio buttons, so we can do the following to skip the built error,

(event: React.ChangeEvent<Record<string, unknown>>) {
console.log(event.target.value);
}

The above code should be used if we have radio button groups.

Otherwise, for a single radio button, this should be used

(event: React.ChangeEvent<unknown>, checked: boolean) {
  console.log(checked);
}

Satyam Saurabh
  • 488
  • 4
  • 16
0
(event: React.SyntheticEvent<HTMLInputElement>) => {
    // use event.currentTarget.value here
}
pseudobbs
  • 214
  • 1
  • 6