Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Material UI Select button label appearing above component

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>
like image 458
Sheku Kanneh Avatar asked Mar 03 '19 01:03

Sheku Kanneh


1 Answers

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

like image 121
Ryan Cogswell Avatar answered Oct 06 '22 00:10

Ryan Cogswell