17
votes

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?

2

2 Answers

34
votes

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});
};
-2
votes

It seems the definition for the change event is incorrect in the SelectInput.d.ts. More here: https://github.com/mui-org/material-ui/issues/15400#issuecomment-484891583

Try to use their recommended signature:

const handleCountryChange = (event: any) => { ... }