3

I'm using just the Select component of Ant Design. I need to select an option and add it to a list, but after selecting the option, I would like to clean the select input.

// Receiving these props
const {
  fields,
  onAdd,
  selected,
} = this.props;

In the code below, when the user select an option, it will call the onAdd method in order to add the selected option to a list in its parent.

<Select
  showSearch
  placeholder="Select a field"
  onSelect={(value) => {
    const optionSelected = fields.filter(field => field.id === value)[0];
    onAdd(optionSelected);
  }
  optionFilterProp="children"
  filterOption={(input, option) => (
    option.props.children.toLowerCase()
      .indexOf(input.toLowerCase()) >= 0
  )}
>
  {
    fields.map(field => (
      <Option
        key={field.id}
        value={field.id}
        disabled={selected.some(item => item.id === field.id)}
      >
        {field.name}
      </Option>
    ))
  }
</Select>

Thanks!

Italo Borges
  • 2,355
  • 5
  • 34
  • 45

2 Answers2

3

I solved my "problem" just setting null to the value property.

<Select
  value={null}
  showSearch
  placeholder="Select a field"
  onSelect={(value) => {
    const optionSelected = fields.filter(field => field.id === value)[0];
    onAdd(optionSelected);
  }
  optionFilterProp="children"
  filterOption={(input, option) => (
  option.props.children.toLowerCase()
    .indexOf(input.toLowerCase()) >= 0
  )}
>
  {
    fields.map(field => (
      <Option
        key={field.id}
        value={field.id}
        disabled={selected.some(item => item.id === field.id)}
      >
        {field.name}
      </Option>
    ))
  }
</Select>

I'm using the select almost as a button, to select and direct add an item on a list. I don't know if this an anti-pattern.

Let me know if anyone has a different approach.

Thanks!

Italo Borges
  • 2,355
  • 5
  • 34
  • 45
1

You need to use ref="someRef" in your JSX template and use it in your onSelect logic.

Additional examples here.

vbuzze
  • 930
  • 1
  • 11
  • 25