简体   繁体   中英

How to set default selected items in Autocomplete

I am using material-ui Autocomplete and I want to add some default selected options to it.

https://codesandbox.io/s/broken-fire-htxtd?file=/src/App.js

As you can see in the example I am rendering pre-selected items with startAdornment. The problem is when I try to select another item, it automatically deletes the pre-selected items. Also I cannot delete them properly.

The idea is this default selected to stay selected until I remove them. Also to be able to pick another letter without erasing them.

you can use defaultValue property instead of Adornment.

 <Autocomplete
  multiple
  open={open}
  onOpen={() => {
    setOpen(true);
  }}
  onClose={() => {
    setOpen(false);
  }}
  options={["A", "B", "C", "D", "E"]}
  disableCloseOnSelect
  defaultValue={cities}  //here
  onChange={(e, v) => setCities(v)}
  getOptionLabel={(option) => option}
  renderOption={(option, { selected }) => {
    if (cities.includes(option)) {
      selected = true;
    }
    return (
      <React.Fragment>
        <Checkbox
          icon={icon}
          checkedIcon={checkedIcon}
          style={{ marginRight: 8 }}
          checked={selected}
        />
        {option}
      </React.Fragment>
    );
  }}
  renderInput={(params) => {
    return (
      <TextField
        {...params}
        variant="outlined"
        label="Cities"
        placeholder="Enter cities"
        autoComplete="off"
      />
    );
  }}
/>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM