Zed
Zed

Reputation: 5921

How to select default option in Material-UI Autocomplete component dynamically?

I am looking for a way to pre-set a default option in a Autocomplete component, just when the ajax call completes loading the list of options. So the use case would be this: when the user opens the page, in the background a list of options would be loaded into state from the ajax response. I want to select the first retrieved option from the list, as soon as it gets loaded. Currently, I just have a basic way to offer a list of options:

  <Autocomplete
     options={defaultProps.options}
     getOptionLabel={option => option.name}
                 renderInput={params => (
                  <TextField {...params} variant="outlined" fullWidth />
     )}
  />

but don't know to select the first one when it gets loaded.

Upvotes: 0

Views: 5957

Answers (2)

FooBar
FooBar

Reputation: 6108

In latest version of Material UI theres an autoHighlight prop.

<Autocomplete
    options={defaultProps.options}
    getOptionLabel={option => option.name}
        renderInput={params => (
        <TextField {...params} variant="outlined" fullWidth />
    )}
    autoHighlight // add this
/>

See the API for Autocomplete

Upvotes: 1

Morta1
Morta1

Reputation: 619

I'm using useEffect to demonstrate an ajax request on component mount.

You can use the value property to set the value after the component has been rendered.

While waiting for the ajax request to resolve, you can use the loading prop to change the component mode to loading

const [options, setOptions] = useState([]);
  const [def, setDef] = useState(null);

  useEffect((()=>{
    setTimeout(()=>{
      const tempArr = [{name:'Subject'},{name:'Another Subject'}];
      setOptions(tempArr);
      setDef(tempArr[0]);
    }, 1000);
  }), []);

  return (
    <div className="App">
      <h1>Autocomplete</h1>
      {<Autocomplete
        options={options}
        loading={!def}
        value={def}
        getOptionLabel={option => option.name}
          renderInput={params => (
              <TextField {...params} variant="outlined" fullWidth />
        )}
      />}
    </div>
  );

Upvotes: 2

Related Questions