Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript React <Select> onChange handler type error

I'm trying to add an onChange event handler to the Select component from material-ui:

<Select
      labelId="demo-simple-select-label"
      id="demo-simple-select"
      value={values.country}
      onChange={handleCountryChange}
    >
      {countries.map(c => {
        return (
          <MenuItem value={c}>{c}</MenuItem>
        )
      })}
    </Select>

and my event handler:

const handleCountryChange = (event: React.ChangeEvent<HTMLSelectElement>) => {
    setValues({...values, country: event.target.value});
  };

but I get the following error:

Type '(event: ChangeEvent) => void' is not assignable to type '(event: ChangeEvent<{ name?: string | undefined; value: unknown; }>, child: ReactNode) => void'.

What's wrong?

like image 322
Desiigner Avatar asked Nov 02 '19 22:11

Desiigner


2 Answers

Since MUI Select in not a real select element you will need to cast e.target.value using as Type and type the handler as React.ChangeEvent<{ value: unknown }>

const handleCountryChange = (event: React.ChangeEvent<{ value: unknown }>) => {
  setValues({...values, country: event.target.value as string});
};
like image 182
Asaf Aviv Avatar answered Nov 05 '22 18:11

Asaf Aviv


This is proper for the latest MUI 5 / Select

  import { SelectChangeEvent } from "@mui/material";

   const handleOnChange = (event: SelectChangeEvent<unknown>) => {
    const value = event.target.value as YourEnumType;
  };
like image 15
httpete Avatar answered Nov 05 '22 20:11

httpete