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>
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With