Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

is it possible to select an object of a Material UI select?

This is in react with material ui, building a select field with a TextField and a ManuItem component. my code:

{data.category?.map((category) => (
     <MenuItem
         key={category.id}
         value={{
             id: category.id,
             percentage: category.percentage,
        }}
     >
         {category.name}
     </MenuItem>

but is giving me this console warning: Material-UI: You have provided an out-of-range value [object Object] for the select...

any idea?

like image 298
Lester Arévalo Avatar asked Dec 17 '25 04:12

Lester Arévalo


1 Answers

This is because TextField accepts only one of the values from the list. In this case, list items are objects and not strings so they don't match and hence the warning.

Here's a working codesandbox with the second approach (using objects as values)

  1. You can either change the value of the items to strings and set the value of TextField as one of the string values.

           <MenuItem
             key={d.id}
             value={d.name}
           >
    
  2. Or you must stringify the json objects as an HTML attribute cannot hold a JSON Object. So, it tries to generate a valid string by using toString() method on object that generates '[object Object]' as its value. Therefore, if you stringify the object, your list item will have a stringified value of the entire object (please note if the object is very large this may not be the optimal approach).

           <MenuItem
             key={d.id}
             value={JSON.stringify({
               id: d.id,
               percentage: d.percentage,
               name: d.name
             })}
           >
    

And add value prop to TextField

      <TextField
        id="outlined-select"
        select
        required
        label="Select"
        variant="outlined"
        onChange={handleChange}
        helperText="Please select a value"
        InputLabelProps={{
          shrink: true
        }}
        value={selectState || ""} // THIS IS NEEDED
        defaultValue={""}
      >
like image 83
Lakshya Avatar answered Dec 19 '25 21:12

Lakshya



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!