Styling MUI Autocomplete with styled-components

Viewed 1659

I have the AutoComplete component from mui in my code, and I'm using it with their TextField component like so:

<StyledAutoComplete
  id="xxx"
  clearOnEscape
  options={[...]}
  renderInput={(params) => (
    <TextField {...params} label="clearOnEscape" variant="standard" />
  )}
/>

Where StyledAutoComplete is the following styled component:

export const StyledAutocomplete = styled(Autocomplete)`
  .MuiAutocomplete-option {
    color: white;
  }
  .MuiAutocomplete-inputRoot {
    color: white;
  }
  .MuiAutocomplete-clearIndicator {
    color: white;
  }
  .MuiAutocomplete-popupIndicator {
    color: white;
  }
`;

This works on some styles (such as the text colour inside the input) but I don't know how I can for example style the input's label or the options' text colour (I tried with .MuiAutocomplete-option from the AutoComplete API docs but that doesn't seem to work). Any help greatly appreciated.

1 Answers

You can design the different parts of the Autocomplete component as you are used to.

In order to render the wanted customizations for the TextField (label), you can pass a StyledTextField.

const StyledTextField = styled(TextField)({
  "& label, & label.Mui-focused": {
    color: "green"
  }
});

In the example, we expect the label to be green in unselected and focus state. In a similar way you can create a StyledOptionBox with your desired changes:

const StyledOptionBox = styled(Box)({
  color: "green"
});

In this example, the options' text colors are expected to be green.

You will need to pass that StyledOptionBox via the renderOption props of your Autocomplete component:

<Autocomplete
  id="xxx"
  clearOnEscape
  options={[
    { id: "test", label: "x" },
    { id: "test2", label: "y" }
  ]}
  renderInput={(params) => (
    <StyledTextField
      {...params}
      label="clearOnEscape"
      variant="standard"
    />
  )}
  renderOption={(props, option) => (
    <li {...props}>
      <StyledOptionBox>{option.label}</StyledOptionBox>
    </li>
  )}
/>

Find it here in a working version: https://codesandbox.io/s/reverent-stallman-tpwkw?file=/src/App.js

More inspiration for changes (and for what is possible) you can find in the Github's Picker example in the MUI documentation.

Related