Home > Software engineering >  Material UI: Select is collapsed, autoWidth not working
Material UI: Select is collapsed, autoWidth not working

Time:10-27

The Material UI (React) Select item is collapsed and doesn't auto expand in width despite autoWidth.

enter image description here

   <FormControl margin="dense">
          <InputLabel id="prefix-label">Prefix</InputLabel>
          <Select
           autoWidth
           labelId="prefix-label"
           id="prefix"
           disabled={formPrefix.disabled}
           value={formPrefix.value ?? ""}
           error={formPrefix.invalid}
           defaultValue={""}
           label="Prefix"
           onChange={handlePrefix}
          >
                 <MenuItem value={""} disabled>
                        Prefix
                 </MenuItem>
                 <MenuItem value={"US"}>US  1</MenuItem>
                 <MenuItem value={"else"}>Else</MenuItem>
          </Select>
          <FormHelperText></FormHelperText>
   </FormControl>

Am I doing something wrong here?

CodePudding user response:

You should add width property to sx prop of FormLabel like:

<FormControl margin="dense" sx={{ width: 100 }}>

You can take a look at this sandbox for live working example.

CodePudding user response:

Add the fullWidth props on <FormControl> component instead of on the <Select> component.

Your JSX code has to be like this

<FormControl margin="dense" fullWidth>
  <InputLabel id="prefix-label">Prefix</InputLabel>
  <Select
    // autoWidth
    // fullWidth
    labelId="prefix-label"
    id="prefix"
    //  disabled={formPrefix.disabled}
    //  value={formPrefix.value ?? ""}
    //  error={formPrefix.invalid}
    defaultValue={""}
    label="Prefix"
    //  onChange={handlePrefix}
  >
    <MenuItem value={""} disabled>
      Prefix
    </MenuItem>
    <MenuItem value={"US"}>US  1</MenuItem>
    <MenuItem value={"else"}>Else</MenuItem>
  </Select>
  <FormHelperText></FormHelperText>
</FormControl>

Edit this code in the CodeSandbox

  • Related