Troubleshooting MaterialUI: Is there a way to prevent the InputLabel text from disappearing when setting a background color on the Select component?

My goal is to change the background color on dropdown elements while keeping the default text visible. Currently, if I don't explicitly set a background color on the Select component, the text specified in the InputLabel displays correctly. However, once I add

style={{backgroundColor: "rgb(232, 241, 250)"}}
to the Select, the InputLabel text disappears. Why does this happen and how can it be fixed?

Here is the relevant code snippet:

<FormControl required fullWidth={true} size="small">
  <InputLabel htmlFor="name" style={{color: "#000"}}>Тема обращения</InputLabel>
  <Select
     variant="filled" 
     style={{backgroundColor: "rgb(232, 241, 250)"}}
     value={props.selectedTheme?.id || ''}
     onChange={(e) => handleChange(e)}>
     {props.themes.map(t => (<MenuItem key={t.id} value={t.id}>{t.name}</MenuItem>))}
  </Select>
</FormControl>

Also included is a screenshot for reference:

https://i.stack.imgur.com/XnCW3.png

Answer №1

Ensure that the variant is specified on the FormControl component rather than on the Select component. Placing it on the Select element causes the InputLabel to not receive the correct styling for the "filled" variant.

Take a look at the initial part of the "filled" style for InputLabel:

  /* The below styles are applied to the root element when `variant="filled"` is used. */
  filled: {
    // Chrome's autofill feature gives the input field a yellow background.
    // Since the input field is placed behind the label in the HTML tree,
    // the input field is painted last and covers the label with an opaque background color.
    // By setting zIndex: 1, the label will be positioned above the input which has opaque background colors.
    zIndex: 1,

Pay attention to the comment explaining the necessity of z-index for elevating the label above opaque backgrounds (such as those set on the Select).

Here is a functional example showcasing the use of variant on the FormControl:

import React from "react";
import { makeStyles } from "@material-ui/core/styles";
import InputLabel from "@material-ui/core/InputLabel";
import MenuItem from "@material-ui/core/MenuItem";
import FormControl from "@material-ui/core/FormControl";
import Select from "@material-ui/core/Select";

const useStyles = makeStyles((theme) => ({
  formControl: {
    margin: theme.spacing(1),
    minWidth: 120
  },
  selectEmpty: {
    marginTop: theme.spacing(2)
  }
}));

export default function SimpleSelect() {
  const classes = useStyles();
  const [age, setAge] = React.useState("");

  const handleChange = (event) => {
    setAge(event.target.value);
  };

  return (
    <div>
      <FormControl
        variant="filled"
        size="small"
        className={classes.formControl}
      >
        <InputLabel
          style={{ color: "#000" }}
          id="demo-simple-select-filled-label"
        >
          Age
        </InputLabel>
        <Select
          style={{ backgroundColor: "rgb(232, 241, 250)" }}
          labelId="demo-simple-select-filled-label"
          id="demo-simple-select-filled"
          value={age}
          onChange={handleChange}
        >
          <MenuItem value="">
            <em>None</em>
          </MenuItem>
          <MenuItem value={10}>Ten</MenuItem>
          <MenuItem value={20}>Twenty</MenuItem>
          <MenuItem value={30}>Thirty</MenuItem>
        </Select>
      </FormControl>
    </div>
  );
}

https://codesandbox.io/s/filled-select-with-background-color-dl1ic?fontsize=14&hidenavigation=1&theme=dark

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is there a way to ensure that the size of the second div box can adjust dynamically in CSS?

Is there a way to make multiple boxes expand dynamically in size when one of them contains more words? Currently, the problem is that only the box with more text expands while the others remain unchanged. I want all the boxes to follow the same size dynami ...

Error: Encountered a TypeError because it is trying to read properties of an undefined value in React, specifically the 'pathname'

It seems like the error is not related to BrowserRouter since it would affect all components. I have looked into the pathname but it is not being used in that specific component. Could someone please assist me? I am unable to find the root cau ...

Ways to achieve a darker background with rgba(0,0,0,0.5)

Hey there, if this isn't the right place to post my query, could someone guide me on where to do so? TL;DR = I need to darken the background of my showcase image! I'm working on a website as part of an online course project to practice new skil ...

Samsung devices exclusively showcase background in responsive design

I am encountering a major problem with my website design, specifically with its compatibility on mobile devices. To ensure its responsiveness, I have tested the design on my iPhone, iPad, and Windows Phone. Unfortunately, since I lack an Android device, I ...

Ensuring that your content expands to fit the sidebar dimensions

I have diligently searched for a solution to my issue both on Google and here, but have yet to find one that works. I've experimented with various CSS properties like display: table-cell and inline-block, as well as different overflow options, but not ...

Why isn't the page showing up on my nextjs site?

I've encountered an issue while developing a web app using nextjs. The sign_up component in the pages directory is not rendering and shows up as a blank page. After investigating with Chrome extension, I found this warning message: Unhandled Runtime ...

Utilizing an Image as a Link in the Background

I am working on a way to convert the CSS background image I have into a clickable link that can be referenced. Here is my CSS code: #wrapper { height: 100%; padding: 66px; } #ad_11 { background-image: url(images/index1.png); display: block; text-indent: ...

Top-notch java tool for caching and minifying dojo, jquery JavaScript, and CSS files

In our project, we have downloaded the Dojo and jQuery libraries from Google CDNs. I am currently seeking a Java tool that can both cache and minify these libraries. The caching process should take place within the ROOT project of Tomcat. While I am awar ...

A complete div component with a minimum height that is sandwiched between a fixed size header and

I'm currently facing a challenge with setting up my webpage due to the height of my elements causing a bit of a frenzy. Specifically, I have a specific layout in mind: At the top, there should be a header that has a fixed height (let's say 150p ...

Looking for a reliable tool to check your CSS classes and tidy up your code effectively?

It seems like a common issue with a straightforward solution. I have numerous CSS selectors scattered across various files, many of which may be unnecessary and a directory full of HTML files. My goal is to identify all redundant selectors in my CSS within ...

Whenever I try to run the npm run dev function on my Ubuntu operating system, I always

After running the npm run dev function, I encountered an error. Just a day ago, everything was working fine. Can someone please help me understand why this error is occurring? Below is the full error response. I would appreciate any assistance as I have sp ...

Simple JavaScript numeric input field

Hey there, I'm a beginner learning JavaScript. I'm currently working on creating a program that adds numbers input through text fields. If you want to check out the HTML code, visit this link on JS Fiddle: http://jsfiddle.net/fCXMt/ My questio ...

Upon modifying the selection, I am notified to utilize the 'defaultValue' or 'value' props on the <select> tag, rather than applying 'selected' on the <option> tag

I am currently working with a material select component: <FormControl fullWidth variant="outlined" className={classes.formControl}> <InputLabel ref={inputLabel} htmlFor="outlined-age-native-simple"> Filial </InputLabel> <Sel ...

Every time I attempt to insert a background image into a div using jQuery, I am consistently faced with a 404 error message

When I hit enter in my search bar, a new div is created each time. However, I am struggling to assign a background image to the created div as I keep receiving a 404 error in the console. Below is the code snippet I'm working with: function appendToD ...

Modifying the div based on the color it is positioned in front of

I am attempting to create a sticky, transparent div that changes its color based on the background behind it. I have both dark and light colored divs, and I want the sticky div to adjust its text color accordingly (white on dark backgrounds, black on light ...

Select a Month and Year with Material UI React

Can we create a month and year picker using Material UI that displays only the month and year (e.g. 2020-09) in the output? ...

What is preventing me from making a call to localhost:5000 from localhost:3000 using axios in React?

I have a React application running on localhost:3000. Within this app, I am making a GET request using axios to http://localhost:5000/fblogin. const Login = () => { const options = { method: "GET", url: "http://localhost:5000/fblogin", ...

Dealing with useEffect being invoked twice within strictMode for processes that should only execute once

React's useEffect function is being called twice in strict mode, causing issues that need to be addressed. Specifically, how can we ensure that certain effects are only run once? This dilemma has arisen in a next.js environment, where it is essential ...

Webpack has encountered a glitch following the refactoring process: There was an error stating that the entry module

Previously, my webpack.js configuration looked like this: const path = require('path'); const {CleanWebpackPlugin} = require('clean-webpack-plugin'); const config = { entry: { index: path.resolve(__dirname, 'src') ...

Excessive text overflowing in a chat interface can be resolved through CSS styling

After conducting a thorough search, it appears that very few individuals are taking this important element into consideration. I currently have a chat interface set up with a div element containing a ul, which then houses li elements that contain p element ...