'How can I make React select component auto matically set to accomodate label width?

I have defined a React select component as follows:

   <FormControl>
      <InputLabel id="demo-simple-select-label">Age</InputLabel>
      <Select
        labelId="demo-simple-select-label"
        id="demo-simple-select"
        label="Age"
      >
        <MenuItem value={10}>Ten</MenuItem>
        <MenuItem value={20}>Twenty</MenuItem>
        <MenuItem value={30}>Thirty</MenuItem>
      </Select>
    </FormControl>

This renders as follows:

  • When not clicked:
    enter image description here
  • When clicked:
    enter image description here

Notice that when not clicked, the label Age is not completely displayed.

I know I can mage label "Age" display completely by having set sx={{minWidth: 80}} on FormControl. But that is not "Automatic". What if my label changes dynamically? I somehow want the select component to adjust width to display label completely. Is it possible?



Solution 1:[1]

import React from 'react';
import Select, { components } from 'react-select';
import makeAnimated from 'react-select/lib/animated';
import 'bootstrap/dist/css/bootstrap.css';

const colourOptions = [] //our array of colours

class App extends React.Component {
  render(){
    return (
      <Select
        className="mt-4 col-md-6 col-offset-4"
        components={makeAnimated()}
        isMulti
        options={colourOptions}
        />
    );
  }
}

export default App;

Solution 2:[2]

I think you can add fullWidth on the FormControl, that can solve your problem, the select component will display well.

You can try my code like below:

<FormControl fullWidth>

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 Harsh2720
Solution 2 wildgamer