Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Material UI Select - object as value fails

in my app I'm using Material UI an React. I created a Select dropdown in order to change the displayed values. So when I change the selection, the data on the page should be updated. Unfortunately, I can't add my object to the value property of the MenuItem. In CodeSandbox it is working with an underlined value, but not in my local environment.

Code: https://codesandbox.io/s/select-exmpl-iosfg

Local error: enter image description here

like image 353
lrefopam Avatar asked Mar 03 '26 06:03

lrefopam


1 Answers

As discussed on chat, this should work.

<Select
  value={plant}
  onChange={handleSelectChange}
  defaultValue={plant}
  displayEmpty
>
  {plants.map((tmpPlant) => (
    //@ts-ignore - necessary to load object into value
    <MenuItem value={tmpPlant}>{tmpPlant.id}</MenuItem>
  ))}
</Select>;

Additionally, it is a good idea to add a key prop to the map function within the MenuItem like so key={tmpPlant.id}

like image 182
Subha Avatar answered Mar 05 '26 20:03

Subha



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!