React | Ant design select value not setting

Viewed 6753

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.

3 Answers

The issue was with using Antd's Form & Form.item along with Select. Code works perfectly fine without the Form

Because the models variable is unchanged. You could apply the below two changes:

One

const models = ['A4', 'A6', 'A8', 'A1', 'Q3', 'Q5'];
const [selected, setSelected] = useState({
  // Initial state
  models,
});

Two

// Get models from `selected`
{map(selected.models, model => <Option value={model} key={model}>{model}</Option>)}

Alex answer is correct. For anyone who need Form.item as parent for Select - it is possible with custom form components. Just create your custom component that render antd Select. And paste your component as only child to Form.item (without any nested elements or wrappers)

<Form.Item>
    <MySelect />
</Form.Item>

Your custom component will automatically receive value and onChange as props. And you can also pass in additional your own props to your custom component. For example field name or data - an array of options for select.

Related