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

When buttons contain an image instead of text, event.target.value will be undefined

I'm facing an issue with two buttons that are almost identical, except one includes an image while the other has text content. I have added onClick event handlers to both of them. Oddly, the event.target.value for the image button is coming up as und ...

I am facing difficulties implementing the delete functionality in my express and react application

I'm currently working on a web project application that enables users to display, add, edit, and delete various web projects they have set up, including three premade projects. Everything is functioning properly except for the delete function. I' ...

Utilize jQuery to extract the content, rearrange the content, and then encapsulate it within fresh

I attempted all day to rearrange this menu the way I want, but since I am new to jQuery, I'm facing some challenges. Here is what I am currently trying to achieve: Inside the last td.top of this menu, there are 3 ul.sub li items. I aim to extract ...

How can I make this div appear on the screen?

I have recently encountered an issue with a navbar on my webpage. Despite adding all the necessary links, one of them mysteriously disappears from view. It seems to be present when inspected in the console, but it just won't display on the front end. ...

No information available at the moment

When the data is not present, it displays as "display none"... However, I want it to show "no data found" This is the current code if (a.innerHTML.toUpperCase().indexOf(filter) > -1) { li[i].style.display = ""; } else { li[i].styl ...

Unable to locate the CSS file

I'm struggling to link a stylesheet file to my 'base.html' template that is used throughout my entire project. Here's the path to the file I want to link: C:\forum_project\static\main\css\style.css Below is ...

Encountering a problem with react-select in typescript when using react-use-form-state

Having a specific and tricky issue that I can't seem to solve right now. Our project has wrappers around certain Form controls to manage all the necessary setup code, and I'm currently facing an issue with the Select component wrapping the Selec ...

What is preventing the determination of the size of my array?

When I call my array "members", it shows as undefined length, which is confusing because Redux DevTools show there is an object in the array. Shouldn't it return the length properly in this case? This issue only arises when I try to submit the form to ...

Ways to turn off hover highlighting

Is there a way to disable the highlighting effect of the <select> element in HTML? When you hover over items in the dropdown list, a blue color strip moves with your mouse. I need to find a way to get rid of this effect. Here is an example of the c ...

Developing data visualizations in React.js

Looking to implement a donut chart similar to the one shown in this image Seeking guidance on how to create this and any recommended libraries for achieving this design. ...

Issue with Material-UI v5 Dialog fade-out animation not functioning properly when used in conjunction with React Router

Currently, I am customizing the React Router Modal Gallery example from their documentation to incorporate Material-UI dialogs. However, I'm facing an issue where the exit animation (fade out) does not play because the URL changes when closing the mod ...

Using HTML and CSS, we can achieve a fixed position using the `position: sticky`

On my website, I have elements that utilize transformations. One issue I've encountered is that these transformations end up resizing the viewport. Normally, I would address this by setting overflow-x: hidden for both html and body, but doing so disru ...

"Encountered a TypeError: Cannot read property 'params

I've encountered an issue with passing the id to my product page. Despite trying various solutions and searching for answers, I still can't get it to work. Below is my index.js code: import React from "react"; import {render} from &quo ...

How to Align the AppBar to the Left in MUI

Is there a way to position the AppBar on the left side of the screen using the React Material UI library from material-ui.com? I am working on a design that requires the global navigation to be displayed along the left side with a fixed position. Additiona ...

What is the best method to remove the x and up/down arrow components of an input date field?

My main objective is to have the orange triangle display in the box, but I'm unsure if CSS or another method is needed to remove the two elements on the left side of the triangle. Is there a way to achieve this? Currently, I am using the input type d ...

Leverage Bootstrap's SASS variables within your React components for streamlined styling

Currently, I am utilizing Bootstrap along with SASS for my React project built using Next.js. The objective now is to integrate the SASS variables from Bootstrap into the scoped SASS modules of the components. /styles/style.scss @import "~bootstrap/s ...

What is the best way to implement handle action for disabling an option in react-select?

Is there a way to create a custom event that will be triggered when a user clicks on a disabled option in a react-select dropdown? The issue is that events do not work when the input is disabled. Any suggestions on how to achieve this? Could wrapping the ...

Leveraging Nextjs Link alongside MUI Link or MUI Button within a different functional component (varieties)

Currently in my development setup, I am utilizing Next.js (10.2) and Material-UI (MUI) with Typescript. In the process, I have implemented a custom Link component: Link.tsx (/components) [...] On top of that, I have created another iteration which functi ...

Why is it that lists always begin outside of the enclosing element?

I've always found this incredibly frustrating. Why do lists behave this way? When you set the margin and padding to 0, you would expect them to align normally with the surrounding text on the left, right? But no. That's where the text within the ...

Implement a vertical scrolling animation in datatables

I am trying to utilize datatables to display all data. My goal is to have the data automatically scroll row by row every 3 seconds. This is my code, and you can also check it out on jsfiddle The intention is to showcase this data on a large screen. < ...