I'm looking for a way to select multiple times the same option.
Currently here is my code:
const [multiSelections, setMultiSelections] = useState<Option[]>(currentSpotSkills);
<Typeahead
id="basic-typeahead-multiple"
labelKey="skill"
multiple
onChange={(nd) => setMultiSelections(nd)}
options={availableSkills!.slice().sort() as Option[]}
placeholder="Rôle..."
selected={multiSelections}
/>
It's perfet to select a set of different options but once an option is selected, it's filtered out of the available list for the user. I get it's because the default filterBy behaviour.
So as a first step, I disabled the filtering with the filterBy props set to () => true
but of course it disabled completely the filtering (I can handle it by writing a custom filterBy quite easily)
The main problem is that it keeps the same ID for each option selected and so when the user tries to remove one selected option from the selected list, it also removes all options with the same label/id
is there any way to be able to select multiple times the same option while keeping those as separated?
If you want to select the same option multiple times and have it be distinct from the other instances, you need to differentiate it somehow. The best way to do this is probably to add a temporary, unique identifier to the option (like an id
) before you save it to your component state. You could use something like lodash.uniqueid
to generate the id and add it to the option in onChange
:
import uniqueId from 'lodash.uniqueid';
const Example = () => {
const [multiSelections, setMultiSelections] = useState([]);
return (
<Typeahead
id="basic-typeahead-multiple"
labelKey="skill"
multiple
onChange={(selections) => {
// If the option already has an `id`, return it,
// otherwise add the identifier.
const newSelections = selections.map((selection) =>
selection.id ? selection : { ...selection, id: uniqueId() }
);
setMultiSelections(newSelections);
}}
options={availableSkills!.slice().sort()}
placeholder="Rôle..."
selected={multiSelections}
/>
);
};
A nice side effect of this approach is that it solves your other problem of filtering out selected options, since the selections won't actually match the initial set of options
you're passing to the typeahead.
Here's a working example: https://codesandbox.io/s/lucid-meitner-9ktti7