Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ant Design - searching for both key and value in a select

If I have a user object with a display name (e.g. "John Smith") and a username (e.g. "johsmi"), how can I search for both display name and username?

This example will only search for usernames, i.e. it will find "johsmi", but not "Smith":

<Select
  showSearch={true}
  optionFilterProp="children"
  placeholder="Select account"
>
  {users.map(user => (
    <Select.Option value={user.name}>
      {user.displayName}                        
    </Select.Option>
  ))}
</Select>

I ended up adding the display name in the key attribute to make it searchable, but I wonder if it's the recommended way of doing it:

<Select.Option key={user.displayName} value={user.name}>
  {user.displayName}                        
</Select.Option>
like image 872
BunnyRabbit Avatar asked Jan 09 '20 09:01

BunnyRabbit


2 Answers

You can use the filterOption props

  const person = [{
    username: 'jstuart123',
    displayName: 'John Stuart'
  }]

  <Select
    showSearch
    optionFilterProp="children"
    onSearch={onSearch}
    filterOption={(input, option) =>  
      option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0 
      || option.props.value.toLowerCase().indexOf(input.toLowerCase()) >= 0
    }
  >
    {person.map(p => <Option value={p.username}>{p.displayName}</Option>)}
  </Select>

Exemple: https://codesandbox.io/s/brave-bhabha-m5tuy

like image 105
rafaelncarvalho Avatar answered Oct 21 '22 03:10

rafaelncarvalho


Works best for me, refer this issue

<Select
  allowClear
  showSearch
  filterOption={(inputValue, option) =>
    option.children.join('').toLowerCase().includes(inputValue.toLowerCase())
  }
>
  {options.map(option=> (
    <Option key={option.id}>{option.name}</Option>
  ))}
</Select>
like image 20
Hustwhw Avatar answered Oct 21 '22 05:10

Hustwhw