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?
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});
};
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;
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With