Ant Design - searching for both key and value in a select
12,039
Solution 1
Try this:
filterOption={(input, option) =>
option.props.value.toLowerCase().indexOf(input.toLowerCase()) >= 0 ||
option.props.label.toLowerCase().indexOf(input.toLowerCase()) >= 0
}
Solution 2
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
Solution 3
I also got an error when I tried the answers above. Actually I solved it like this.
filterOption={(input, option) =>
option.value.toLowerCase().indexOf(input.toLowerCase()) >= 0 ||
option.value.toLowerCase().indexOf(input.toLowerCase()) >= 0
}
Related videos on Youtube
Author by
BunnyRabbit
Updated on June 04, 2022Comments
-
BunnyRabbit almost 2 years
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>
-
AugDog about 3 yearsThank you! One of those
option.value
s should beoption.label
to search both the label and value, though. -
Gavin Thomas over 2 yearsThis causes an error.
-
rafaelncarvalho over 2 years@GavinThomas which error?
-
WW00WW over 2 years@AugDog shouldn't it be
option.children
? -
James Tan about 2 yearsim using with vuejs, and 1 way todo it is to add data-prop to a-select-option, and getting it via option.props[data-label'].toLowerCase()...
-
okebinda about 2 years@rafaelncarvalho For me it's a warning: 'Return type is option instead of Option instance. Please read value directly instead of reading from
props
.' To remove the warning removeprops
from thefilterOption
chain, like this:option.children.toLowerCase()...