Search code examples
javascriptreactjsmaterial-uimultiple-select

React js Multiple Select [object Object], [object Object]


I`m using Material UI to make a multiple Select. This is my code.

  <TextField
        classes={{ root: classes.root }}
        select
        name="states"
        id="states"
        fullWidth
        label="states where you want to work" 
        SelectProps={{
          multiple: true,
          value: states.states,
          onChange: handleFieldChange
        }}
      >
        {listStates.map(col => (
              <MenuItem selected classes={{ selected: classes.selected }} key={col} value={col}>
                  <Checkbox checked={states.states.indexOf(col) > -1} />
                  <ListItemText primary={col} />
              </MenuItem>
            ))} 
      </TextField>

Here is the handleFieldChange function:

  const handleFieldChange = event => {
      event.persist();
      setStates(states => ({
        ...states,
        [event.target.name]:
          event.target.type === "checkbox"
            ? event.target.checked
            : event.target.value
      }));
    };

And here is the array of States:

const listStates = [ "Aguascalientes", "Baja California", "Baja California Sur", "Campeche", "CDMX", "Coahuila de Zaragoza", "Colima", "Chiapas", "Chihuahua", "Durango", "Guanajuato", "Guerrero", "Hidalgo", "Jalisco", "EDOMEX", "Michoacán de Ocampo", "Morelos", "Nayarit", "Nuevo León", "Oaxaca", "Puebla", "Querétaro", "Quintana Roo", "San Luis Potosí", "Sinaloa", "Sonora",  "Tabasco",  "Tamaulipas",  "Tlaxcala", "Veracruz de Ignacio de la Llave", "Yucatán", "Zacatecas"];

Everything work fine, the values save in the useState correctly, but in the screen I dont see the values I selected, I only see [object Object], [object Object].

Do you know why it´s happening??

Regards


Solution

  • The issue seems to be a missing props renderValue. value is the list of values selected but renderValue function gives the actual rendering logic. Pass this additional props and it should work fine.

    As per the official docs:
    renderValue is function(value: any) => ReactNode where value - the value provided to the component.

    Sample Code:

    SelectProps={{
      multiple: true,
      value: states.states,
      onChange: handleFieldChange,
      renderValue: (data) => <div>{data.join(", ")}</div>
    }}
    

    Hope it helps. Revert for any doubts/clarifications.