Jamie Hutber
Jamie Hutber

Reputation: 28126

Mui v5 styleOverrides not working with themes

I am trying to style using theme overrides as laid out in the documentation here:

I have the following code sandbox:

import * as React from 'react';
import { ThemeProvider, createTheme } from '@mui/material/styles';
import Select from '@mui/material/Select'
import MenuItem from '@mui/material/MenuItem'

const theme = createTheme({
  components: {
    MuiSelect: {
      styleOverrides: {
        root: {
          background: '#000',
        },
      },
    },
  },
});

export default function GlobalThemeOverride() {
  return (
    <ThemeProvider theme={theme}>
          <Select
            labelId="demo-simple-select-label"
            id="demo-simple-select"
            variant="standard"
          >
            <MenuItem value={10}>Ten</MenuItem>
            <MenuItem value={20}>Twenty</MenuItem>
            <MenuItem value={30}>Thirty</MenuItem>
          </Select>
    </ThemeProvider>
  );
}

The Select box should have a background of #fff however no background is set at all. :(

Upvotes: 12

Views: 15932

Answers (1)

Ryan Cogswell
Ryan Cogswell

Reputation: 81156

This looks like a bug to me (or at least missing a feature that is reasonable for developers to expect to be there). The issue is that Select doesn't define any styles of its own at the root level, so it doesn't leverage the code (which would be a call to MUI's styled such as here for the select class) that would take care of looking at the theme and applying the corresponding style overrides. I recommend logging an issue.

There are a couple possible workarounds.

Workaround 1 - Target the select CSS class

This approach may work, but it depends on what all you are trying to do since this targets a child of the root element.

const theme = createTheme({
  components: {
    MuiSelect: {
      styleOverrides: {
        select: {
          backgroundColor: "#000",
          color: "#fff"
        }
      }
    }
  }
});

Edit GlobalThemeOverride Material Demo (forked)

Workaround 2 - Target the MuiInput-root CSS class

The approach below targets the same element as MuiSelect-root by leveraging MuiInput-root (the rendering of the root element of the Select is delegated to the Input component when the variant is "standard") and then qualifying it via "&.MuiSelect-root" so that it only affects Select rather than all inputs.

const theme = createTheme({
  components: {
    MuiInput: {
      styleOverrides: {
        root: {
          "&.MuiSelect-root": {
            backgroundColor: "#000",
            color: "#fff"
          }
        }
      }
    }
  }
});

Edit GlobalThemeOverride Material Demo (forked)

Upvotes: 8

Related Questions