Search code examples
reactjsreact-bootstrapreact-bootstrap-typeahead

React-Bootstrap-Typeahead: Clear on Menu Selection


In my React-Bootstrap-Typeahead I need to set a state var and clear in the input immediately to allow new searches. What's happening now is:

  1. A list of suggestions is presented
  2. When I select a menu item, my handleChange is executed correctly
  3. The selection is shown in the text field.

I need to set the var clickedSelection and reset the input for new searches. Everything should be cleared and closed. (Note: I'm using the AsyncTypeahead variation of React-Bootstrap-Typeahead .)

const [isLoading, setIsLoading] = useState(false);
const [searchResults, setSearchResults] = useState([]);
const [clickedSelection, setClickedSelection] = useState({});

// Fetch Function
const fetchResults = async (token) => {
   setIsLoading(true);
   const response = await axios.get('/myurl/search/' + token); // Axios for Data Fetch
   setSearchResults(response.data); // Set results state var
}

// Handle onChange Function: set 'clickedSelection'
const handleChange = (options) => {
   console.log(JSON.stringify(options[0]);
   setClickedSelection(options[0]);
}

<AsyncTypeahead
    isLoading={isLoading}
    onSearch={(query) => {
       fetchResults(query)
    }}
    option={searchResults}
    labelKey={option => `${option.firstName ${option.lastName}`}
    onChange={handleChange}
/>

Solution

  • You can set a ref on the typeahead and use the public clear method to clear the selections in your onChange handler:

    const typeaheadRef = useRef(null);
    
    const handleChange = (selected) => {
      setClickedSelection(selected[0]);
      typeaheadRef.current.clear();
    };
    
    return (
      <AsyncTypeahead
        ...
        onChange={handleChange}
        ref={typeaheadRef}
      />
    );
    

    Working sandbox: https://codesandbox.io/s/purple-flower-0t5m8