I am trying to add Select All / Unselect All to React Antd's 'SELECT' component.
My code
const models = ['A4', 'A6', 'A8', 'A1', 'Q3', 'Q5'];
const [selected, setSelected] = useState({
models: [],
});
console.log('selected', selected);
const handleModelSelect = (option) => {
if (option === 'all') {
if (selected.models.length === models.length) {
setSelected((prev) => ({ ...prev, models: [] }));
} else {
setSelected((prev) => ({ ...prev, models }));
}
} else {
setSelected((prev) => ({ ...prev, models: uniq([...prev.models, option]) }));
}
};
return
(<Form>
<Form.Item
name="model"
style={{ display: 'inline-block', width: 'calc(33% - 8px)' }}
>
<Select mode="multiple" placeholder="Models" value={selected.models} onSelect={handleModelSelect}>
<Option value="all">Select all</Option>
{map(models, model => <Option value={model} key={model}>{model}</Option>)}
</Select>
</Form.Item>
</Form>)
I see that I do get everything selected & unselected in the "selected.models", however the issue is that the Select component visually does NOT update itself, meaning it stays with things I have selected/unselected.
Really weird behavior.
The issue was with using Antd's Form & Form.item along with Select. Code works perfectly fine without the Form