To achieve the desired layout, you can specify the min-width
of the InputLabel
to be equal to the width of its content by setting it to max-content
.
Then, during rendering, calculate the offsetWidth
of the InputLabel
and apply this value as the minimum width for the FormControl
.
const SimpleSelect = () => {
const classes = useStyles();
const [age, setAge] = React.useState("");
const [labelWidth, setLabelWidth] = React.useState();
const labelRef = React.useRef();
const handleChange = (event) => {
setAge(event.target.value);
};
React.useEffect(() => {
setLabelWidth(`${labelRef.current.offsetWidth + 24}px`);
}, [labelRef]);
return (
<div>
<FormControl
required
className={classes.formControl}
style={{
minWidth: labelWidth
}}
>
<InputLabel
id="demo-simple-select-required-label"
style={{ minWidth: "max-content" }}
ref={labelRef}
>
The label
</InputLabel>
<Select
value={age}
onChange={handleChange}
className={classes.selectEmpty}
>
<MenuItem value="">
<em>None</em>
</MenuItem>
<MenuItem value={10}>An option</MenuItem>
</Select>
</FormControl>
</div>
);
};
Check out this demo on CodeSandbox
Additionally, remember that the FormControl
component has a fullWidth
prop which, when set to true
, will make the component expand to fill its container's width entirely.