Search code examples
reactjsmaterial-ui

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?


Solution

  • 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={""}
          >