MUI Autocomplete - Make all options selected by default

Viewed 366

I've be using this example to try and get the values in the autocomplete drop down to be automatically selected by default. I'm looking to get all the values to be selected when the page is loaded. Does anyone know how to do this?

Sandbox code : https://codesandbox.io/s/s26gz?file=/demo.js:504-523

2 Answers

You can control the value of the Autocomplete by overriding the value/onChange props and use useState to set the initially selected options:

const [value, setValue] = React.useState(options);

return (
  <Autocomplete
    options={options}
    value={value}
    onChange={(e, v) => setValue(v)}
    {...}
  />
);

Or if you're using uncontrolled mode, simply pass a defaultValue:

<Autocomplete
  defaultValue={options}
  {...}
/>

Codesandbox Demo

You can pass a defaultValue props to Autocomplete like this

  <Autocomplete
    options={options}
    value={value}
    defaultValue={top100Films}
    ...
  />
Related