Search code examples
reactjsmaterial-ui

How can I change the width of Material UI Autocomplete popover


When using the Select from Material-UI, there's a prop there called 'autoWidth' which sets the width of the popover to match the width of the items inside the menu.

Is there a similar option for the Autocomplete component?

what i'm trying to achieve is that the width of the TextField is independent of the width of the menu, and the width of the menu is determined by the menu items rather than a hard-coded 'width.

What I managed to find so far is an option to provide width to the 'paper' component using classes (see code below), but it's independent of the actual items' width and the position of the paper isn't adjusted to stay inside the window.

const styles = (theme) => ({
  paper: {
    width: "450px"
  }
});

function ComboBox(props) {
  return (
    <Autocomplete
      id="combo-box-demo"
      options={top100Films}
      classes={{
        paper: props.classes.paper
      }}
      getOptionLabel={(option) => option.title}
      style={{
        width: 300,
        paddingLeft: "100px"
      }}
      renderInput={(params) => (
        <TextField {...params} label="Combo box" variant="outlined" />
      )}
    />
  );
}

link to codesandbox

What i'm trying to achieve is a similar behavior to this codesandbox but using the Autocomplete component. Notice that width of the pop-up menu is taken from the menu items while the width of the Select component is hard-coded.


Solution

  • To have a dynamic menu based on elements inside the menu itself you need to customize the Autocomplete's PopperComponent property in this way:

    1. Define a custom Popper:

      const PopperMy = function (props) {
         return <Popper {...props} style={styles.popper} placement="bottom-start" />;
      };
      
    2. In Popper style, set the width to "fit-content":

      const styles = (theme) => ({
         popper: {
            width: "fit-content"
         }
      });
      
    3. Pass the component PopperMy to Autocomplete:

      <Autocomplete
         PopperComponent={PopperMy}
         ...  
      />
      

    Here is your codesandbox modified.