How do I use the Dropdown component's searchQuery prop without breaking the display text?

14 Views Asked by At

I am rendering a Dropdown component from semantic-ui-react. When I set the searchQuery prop, then the display text does not appear correctly for the selected option. Instead, it always displays the most recent query. I tried explicitly setting the text prop based on the selected value, but it still only shows the most recent query. How do I use the searchQuery prop without breaking the display text?

This code demonstrates the problem. Remove query, setQuery, searchQuery, onSearchChange, and text to see how it works (as expected) without the searchQuery prop.

import React, { useState } from 'react'
import { Dropdown } from 'semantic-ui-react'

const countryOptions = [
  { key: 'af', value: 'af', flag: 'af', text: 'Afghanistan' },
  { key: 'ax', value: 'ax', flag: 'ax', text: 'Aland Islands' },
  { key: 'al', value: 'al', flag: 'al', text: 'Albania' },
]

const DropdownExampleSearchSelection = () => {
  const [value, setValue] = useState(null);
  const [query, setQuery] = useState('');
  const text = countryOptions.find(o => o.value === value)?.text;
  
  return (
    <div>
      <p>value: {value}</p>
      <p>text: {text}</p>
      <Dropdown
        placeholder='Select Country'
        fluid
        search
        selection
        options={countryOptions}
        searchQuery={query}
        onSearchChange={(e, { searchQuery }) => setQuery(searchQuery)}
        value={value}
        onChange={(e, { value }) => setValue(value)}
        text={text}
      />
    </div>
  );
}

export default DropdownExampleSearchSelection
1

There are 1 best solutions below

0
srk On

It seems to work if I clear the query when the user makes a selection. The text prop is not needed.

onChange={(e, { value }) => {
  setQuery(undefined);
  setValue(value);
}}

Full working example:

import React, { useState } from 'react'
import { Dropdown } from 'semantic-ui-react'

const countryOptions = [
  { key: 'af', value: 'af', flag: 'af', text: 'Afghanistan' },
  { key: 'ax', value: 'ax', flag: 'ax', text: 'Aland Islands' },
  { key: 'al', value: 'al', flag: 'al', text: 'Albania' },
]

const DropdownExampleSearchSelection = () => {
  const [value, setValue] = useState(null);
  const [query, setQuery] = useState('');
  
  return (
    <Dropdown
      placeholder='Select Country'
      fluid
      search
      selection
      options={countryOptions}
      searchQuery={query}
      onSearchChange={(e, { searchQuery }) => setQuery(searchQuery)}
      value={value}
      onChange={(e, { value }) => {
        setQuery('');
        setValue(value);
      }}
    />
  );
}

export default DropdownExampleSearchSelection