Change the color of MUI Autocomplete option

Viewed 9192

I'm using the Autocomplete of Material UI and I have a list with the attribute Color. I have to render option by option with the respective color in option background.

Here's a example:

import React from "react";
import TextField from "@material-ui/core/TextField";
import Autocomplete from "@material-ui/lab/Autocomplete";

export default function ComboBox() {
  return (
    <Autocomplete
      id="combo-box-demo"
      options={top100Films}
      getOptionLabel={option => option.title}
      style={{ width: 300 }}
      renderInput={params => {
        return (
          <TextField
            {...params}
            label="Combo box"
            variant="outlined"
            fullWidth
          />
        );
      }}
    />
  );
}

const top100Films = [
  { title: "The Shawshank Redemption", year: 1994, color: '#FF0000' },
  { title: "The Godfather", year: 1972, color: '#FF5555' },
  { title: "Avatar", year: 2010, color: '#FFFFFF' },
  // Plus a bunch more
];
2 Answers

You can use renderOption to render the style conditionally for each option in the latest version of MUI.

<Autocomplete
  renderOption={(props, option) => {
    const { title, color } = option;
    return (
      <span {...props} style={{ backgroundColor: color }}>
        {title}
      </span>
    );
  }}
  {...}
/>

Live Demo

Edit 64171767/change-the-color-of-material-ui-autocomplete-option

You can change the CSS like this:

.MuiAutocomplete-inputRoot[class*="MuiOutlinedInput-root"] {
    background: #ffff
}
Related