Search code examples
reactjsselectdropdownantd

How search the option from select dropdown which search from first letter using antd?


(eg) options in the list (USD, AUD, EUR) If I search 'U' it should display 'USD' only

<Select
    showSearch
    style={{ width: 200 }}
    placeholder="Select a person"
    optionFilterProp="children"
    onChange={onChange}
    onFocus={onFocus}
    onBlur={onBlur}
    onSearch={onSearch}
    filterOption={(input, option) =>
      option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
    }
  >

It getting all the list value which all have 'U'

How can set the filterOption in select

Thanks in advance <3

Link to refer CodeSandBox Select


Solution

  • Instead of checking where indexOf >= 0, use === instead, to force it to only check if it's matched at the start of the string:

    filterOption={(input, option) =>
      option.props.children.toLowerCase().indexOf(input.toLowerCase()) === 0
    }
    

    Updated codesandbox here. You'll see it matches Lucy only on L, and not on U.

    Alternatively, you can use .startsWith():

    filterOption={(input, option) =>
      option.props.children.toLowerCase().startsWith(input.toLowerCase())
    }