user2683470
user2683470

Reputation: 189

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, i.e. 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

Upvotes: 4

Views: 7982

Answers (1)

Ryan Cogswell
Ryan Cogswell

Reputation: 81016

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

Upvotes: 7

Related Questions