react-bootstrap-typeahead

React-Bootstrap-Typeahead: Capture moment before setting selection into box (to allow conditional rejection)


In React-Boostrap-Typeahead, I need to capture the moment after the mouse has been clicked, but before the menu selection gets loaded into the Typeahead's box.

This is because I need to check items being selected, and for some of them, I need to display an alert with a Yes/No warning. Only if Yes is clicked can I proceed with setting that value into the box. Otherwise I need to reject the selection and keep it whatever it was prior to the mouse click.

If there are any workarounds please let me know.


Solution

  • You should be able to achieve what you're after using onChange:

    const ref = useRef();
    const [selected, setSelected] = useState([]);
    
    return (
      <Typeahead
        id="example"
        onChange={(selections) => {
          if (!selections.length || window.confirm('Are you sure?')) {
            return setSelected(selections);
          }
          ref.current.clear();
        }}
        options={options}
        ref={ref}
        selected={selected}
      />
    );
    

    Working example: https://codesandbox.io/s/objective-colden-w7ko9