jquense / react-widgets

Polished, feature rich, accessible form inputs built with React
http://jquense.github.io/react-widgets/
MIT License
2.34k stars 395 forks source link

How to stablish the value on open DropdownList #1146

Closed davidrojo closed 1 year ago

davidrojo commented 1 year ago

Hi,

Currently when a value is selected, and you click the DropdownList, the current value is shown but the cursor is at the beginning of the text, so if you write you start writing a new word and you loose the current value.

I want the cursor to be at the end of the current value when you click the DropdownList, and as you write, the written text is appended to the current value at the end, just like a normal input text works.

How can I accomplish this?

Thanks

davidrojo commented 1 year ago

I think this is the same issue but has no answers: https://github.com/jquense/react-widgets/issues/1117

jquense commented 1 year ago

That's not how a drop-down works generally, the text inputs is just for filtering it's not the "value" of the drop-down. The filter input is empty when you focus the input. If you want to control what the starting search term is you can control and provide the searchTerm prop

davidrojo commented 1 year ago

Thanks, that is what I was looking for. A little bit of state management and I've been able to accomplish what I needed.

For those in the same situation, What I've done is maintain the searchTerm in a state variable, and update it on onSearch. Also added a useEffect when the DropdownList is open to establish again the filter, as when the DropdownList closes it sets the filter to empty string.

  // defaultFilter is a variable with the filter I want to be shown on open. 
  // When a value is selected in the dropdown I update defaultFilter to the new value, so on open, the new value is used as filter
  const [filter, setFilter] = useState(defaultFilter);
  const [isOpen, setIsOpen] = useState(false);

  useEffect(() => {
    if (isOpen) {
      setFilter(defaultFilter);
    }
  }, [isOpen]);

  return (
    <DropdownList
      onSearch={ search => { setFilter(search); } }
      searchTerm={ isOpen ? filter : '' }
      onToggle={ isOpen => setIsOpen(isOpen) }
      ....
    />