'React prevent MUI Select from changing width in MUI Grid
I have an MUI grid setup with a variable number of columns. Currently, if the user selects a long string for the Select box, the Select grows, increasing the size of the entire column. However, I want each column to remain the same size, no matter what is selected (and truncate what's in the Select box).
Please see the images below for a better understanding. In these examples, there are 8 columns:
Unfilled: empty fields
Filled: field filled, clearly the long text in the select box resized the whole column
Code:
{this.state.sampleData.map((obj, idx) => {
return (
<Grid item xs={true}> //Ensures the columns are the correct size (more columns = smaller widths).
<Grid container spacing={1}>
<Grid item xs={12}>
<Typography>#{obj["#"]}</Typography>
</Grid>
<Grid item xs={12}>
<TextField
className={classes.smallTextField}
inputProps={{
...
}}
variant="outlined"
label="Name"
name="name"
value={
this.state.sampleData[idx].name || ""
}
onChange={(event) => {
this.handleChange(
event.target.value,
idx,
"name"
);
}}
/>
</Grid>
<Grid item xs={12}>
<FormControl
variant="filled"
fullwidth
size="small"
className={classes.selectFieldFormControl}
>
<InputLabel
sx={{ ... }}
>
Position
</InputLabel>
<Select
sx={...}
name="position"
value={
this.state.sampleData[idx].position || ""
}
onChange={(event) => {
this.handleChange(
event.target.value,
idx,
"position"
);
}}
>
<MenuItem value="">
<em>None</em>
</MenuItem>
<MenuItem value={"manager"}>
manager
</MenuItem>
<MenuItem value={"factory"}>
factory
</MenuItem>
<MenuItem value={"assistant to the regional manager"}>
assistant to the regional manager
</MenuItem>
</Select>
</FormControl>
</Grid>
</Grid>
);})}
How can I get the box to truncate the text inside it so that the column does not get resized? I figure I'll need to add some style in either the Select box itself or the parent grid item.
Thanks!
Solution 1:[1]
I had the same problem, adding a maxWidth of 100% to the grid item that contains the select, and making the width of the select 100% solved it for me:
<Grid item xs={12} lg={4} sx={{ maxWidth: "100% !important" }}>
<h3 id="select-theme-label">Themes</h3>
<Select
id="select-theme"
sx={{ width: "100%" }}
></Select>
</Grid>
Or probably more realistically, adding the right maxWidth responsively:
sx={{ maxWidth: { xs: "100% !important", md: "28% !important" } }}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 |