Search code examples
cssreactjsmaterial-ui

How can I center the options from a MUI autocomplete and to wrap them in a border?


I need to center the options from a MUI autocomplete but I tried many ways but still a failure. Also I need to wrap each option in a border. I tried to add it to inputProps and in a style paper component but it didn't work this is my code so far:

const PlacementCell = ({ value, placements, notAvailable = false, readOnly = false }: PlacementCellProps): ReactElement => {
  const { palette, spacing } = useTheme();
  const [selectedPlacement, setSelectedPlacement] = useState<Placement | undefined>(value || placements[0]);

  const handlePlacementChange = (event: React.SyntheticEvent, newValue: Placement | null) => {
    if (newValue !== null) {
      setSelectedPlacement(newValue);
    }
  };

const CustomListbox = styled('ul')({
  [`& .${autocompleteClasses.option}`]: {
    display: 'flex',
    justifyContent: 'center',
  },
});

  return (
    <Stack
      direction="row"
      height={1}
      alignItems="center"
      spacing={2}
      justifyContent="space-between"
    >
      <Autocomplete
        options={placements}
        getOptionLabel={(option) => option.placementName}
        renderInput={(params) => (
          <TextField
            placeholder="Select"
            {...params}
            InputProps={{
          ...params.InputProps,
          disableUnderline: true,
            }}
            inputProps={{
              ...params.inputProps,
              style: { textAlign: 'center' },
            }}
            sx={{
              [`& .${autocompleteClasses.inputRoot} .MuiInput-input`]: {
                padding: '12px',
              },
              variant: 'bodySmall.default',
              [`& .${autocompleteClasses.popupIndicator}`]: {
                right: 12,
                ['&:hover']: {
                backgroundColor: 'transparent',
                },
              },
            }}
          />
        )}
        // PaperComponent={CustomPaper}
        fullWidth
        disableClearable
        onChange={handlePlacementChange}
      />
    </Stack>
  );
};

Here is an image of what I have to display enter image description here

Thanks for any suggestion!


Solution

  • You should use slotProps on your Autocomplete like mentioned here: https://stackoverflow.com/a/78267213/11184255

    So it would look something like that

    <Autocomplete
    ...
      slotProps={{
        paper: {
          sx: {
            '& .MuiAutocomplete-listbox': {
              '& .MuiAutocomplete-option': {
                display: 'flex',
                justifyContent: 'center',
                border: '1px solid lightgray',
                margin: '5px'
              },
            },
          },
        },
      }}
    />