Search code examples
reactjsmaterial-uimui

MaterialUI label text disappearing and can not change or choose dropdown menu elements


I need to change selected item background color without using important.I find this example in github.But I need to create MuiThemeProvider to change background color of selected element. (Actually I need to set it as transparent)

When I add MuiThemeProvider as a parent to MenuItem label text disappear and user can not choose one of menu element.In console I get an error.

Warning: Function components cannot be given refs. Attempts to access this ref will fail. Did you mean to use React.forwardRef()?

<FormControl className={classes.formControl}>
    <Select
      id="demo-simple-select"
      displayEmpty
      value={age}
      onChange={handleChange}
    >
      <MuiThemeProvider theme={theme}>
        <MenuItem value={10}>Ten</MenuItem>
        <MenuItem value={20}>Twenty</MenuItem>
        <MenuItem value={30}>Thirty</MenuItem>
      </MuiThemeProvider>
    </Select>
</FormControl>

And theme code

const theme = createMuiTheme({
  overrides: {
    MuiMenuItem: {
      root: {
        "&$selected": {
          backgroundColor: "red"
        }
      }
    }
  }
});

Codesandbox example


Solution

  • Figure out.Actually I need to add MuiThemeProvider as a parent to FormControl not to MenuItem.Maybe this answer help someone.

    Codesandbox

    <MuiThemeProvider theme={theme}>
      <FormControl className={classes.formControl}>
        <Select
          id="demo-simple-select"
          displayEmpty
          value={age}
          onChange={handleChange}
        >
          <MenuItem value={10}>Ten</MenuItem>
          <MenuItem value={20}>Twenty</MenuItem>
          <MenuItem value={30}>Thirty</MenuItem>
        </Select>
      </FormControl>
    </MuiThemeProvider>