5
votes

Trying to use the Material UI select component with FormControl and InputLabel, the the label of the select always renders above the select component and I cannot figure out why.

my code looks something like this

 <FormControl>
      <InputLabel htmlFor="hey">A Label</InputLabel>
      <Select inputProps={{
         id: "hey"
      }} value="Hey">
          <MenuItem value="Hey">
             Hey
          </MenuItem>
      </Select>
   </FormControl>
2
What are you expecting it to do? That is also where the label appears in the Material UI demos.Ryan Cogswell
@RyanCogswell in the demos the label sits in the Select box then moves up when the Select box is clicked. At least it does on Google ChromeSheku Kanneh

2 Answers

4
votes

The label will only sit in the Select box if the currently selected option has an empty value; otherwise it needs to show the selected item instead and the label has to be up out of the way. In your example, you only have a single option in your Select with a value of "Hey" so that will start out selected and that will be shown.

Here's an example showing side-by-side your sample Select and one that starts with an empty value selected:

import React, { useState } from "react";
import ReactDOM from "react-dom";

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

const styles = theme => ({
  formControl: {
    margin: theme.spacing.unit,
    minWidth: 120
  }
});

function App({ classes }) {
  const [value, setValue] = useState("");
  return (
    <>
      <FormControl className={classes.formControl}>
        <InputLabel htmlFor="hey">A Label</InputLabel>
        <Select
          inputProps={{
            id: "hey"
          }}
          value="Hey"
        >
          <MenuItem value="Hey">Hey</MenuItem>
        </Select>
      </FormControl>
      <FormControl className={classes.formControl}>
        <InputLabel htmlFor="hey2">A Label</InputLabel>
        <Select
          inputProps={{
            id: "hey2"
          }}
          value={value}
          onChange={event => setValue(event.target.value)}
        >
          <MenuItem value="">Empty Value for First Option</MenuItem>
          <MenuItem value="Hey">Hey</MenuItem>
        </Select>
      </FormControl>
    </>
  );
}
const StyledApp = withStyles(styles)(App);
const rootElement = document.getElementById("root");
ReactDOM.render(<StyledApp />, rootElement);

Edit Labelled Select

1
votes

I had this issue when using material-ui v3.9.2. I updated to the latest version (currently v4.5.0) and that fixed it for me.