Search code examples
react-bootstrap-typeahead

Clear input upon onChange event


I'd like to clear the input field after a successful selection (in single selection mode) - I'm aware that this isn't a normal use-case so I'm not surprised I couldn't find a way to do it in the docs. Is there a workaround I could use?


Solution

  • The typeahead instance exposes a public clear method, which you can use in the onChange handler to reset the component after a successful selection:

    const MyTypeahead = () => {
      const typeaheadRef = useRef(null);
    
      return (
        <Typeahead
          ...
          onChange={s => {
            if (s.length) {
              typeaheadRef.current.clear();
            }
          }}
          options={[ ... ]}
          ref={typeaheadRef}
        />
      );
    };
    

    Working example: https://codesandbox.io/s/rbt-clear-on-change-59kgq