Search code examples
reactjsautosuggest

Programmatically show suggestions for react-autosuggest


I am using the react-autosuggest library here: https://react-autosuggest.js.org/ Now I have the list of input suggestions pop up below the input box when the user clicks in the input box, similar to a dropdown list. But I have also added a font-awesome down arrow inside the input box. When that is clicked, nothing happens. I just want it to show the list same focusing the actual input box.

Here is how I am rendering the input component:

    const renderInputComponent = (inputProps) => (
        <div className="inputContainer">
            {selectedCustomer ? (
                <FontAwesomeIcon
                    icon={faTimes}
                    size={'1x'}
                    onClick={() => {
                        setSelectedCustomer('');
                        setSuggestionValue('');
                    }}
                />
            ) : (
                <FontAwesomeIcon
                    icon={faAngleDown}
                    size={'1x'}
                    onClick={() => {
                      ??? <-- this is where I think I would put something to show those suggestions
                    }}
                />
            )}
            {/*<input {...inputProps} ref={autosuggestInput} />*/}
            <input {...inputProps} />
            {/* when I add in the above commented to code to show options when the caret is clicked, I get an error: https://github.com/moroshko/react-autosuggest/pull/631 */}
        </div>
    );

I have created a Code Sandbox demonstrating my request. I added the comment where I think the code should go. https://codesandbox.io/s/compassionate-ramanujan-yi9i8?file=/src/App.js

And here is an image:

enter image description here

That dropdown caret icon should show all the results the same as clicking in the box does:

enter image description here


Solution

  • You can trigger the dropdown by focusing in on the input. To do this, just create a ref to it:

    const autosuggestInput = useRef(null);
    
    ...
    
    <input {...inputProps} ref={autosuggestInput} />
    

    And when the dropdown icon is clicked, call setFocus() on the element

    <FontAwesomeIcon
      icon={faAngleDown}
      size={"1x"}
      onClick={() => {
        autosuggestInput.current.focus();
      }}
    />
    

    You can find a forked repo where this is fixed here: https://codesandbox.io/s/confident-bash-bu789?file=/src/App.js:2875-3047