简体   繁体   中英

How to remove a selected Chip outside of Autocomplete in material UI

So I want to display selected values as <Chip /> outside of the <TextField /> in <Autocomplete /> . I was able to display values as state . However, I still have trouble deleting those chips, ie not just the display, but also change the selected prop in <Autocomplete /> . Does anyone have an idea?

  const [val, setVal] = useState([]);

  const valHtml = val.map((option, index) => (
    <Chip
      label={option.title}
      deleteIcon={<RemoveIcon />}
      onDelete={() => {}}
    />
  ));

  return (
    <div>
      <Autocomplete
        multiple
        filterSelectedOptions
        options={top100Films}
        onChange={(e, newValue) => setVal(newValue)}
        getOptionLabel={option => option.title}
        renderTags={() => {}}
        renderInput={params => (
          <TextField
            {...params}
            variant="standard"
            placeholder="Favorites"
            margin="normal"
            fullWidth
          />
        )}
      />
      <div className="selectedTags">{valHtml}</div>
    </div>
  );
}

Complete code here

You need two things:

  1. Appropriate logic in the onDelete of the Chip such as:
      onDelete={() => {
        setVal(val.filter(entry => entry !== option));
      }}
  1. Specify the value (which you are already managing in state) on the Autocomplete :
      <Autocomplete
        value={val}
        // ... other properties
      />

Here is a working version of your sandbox: https://codesandbox.io/s/autocomplete-with-chips-85rqq

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