ericgio / react-bootstrap-typeahead

React typeahead with Bootstrap styling
http://ericgio.github.io/react-bootstrap-typeahead/
MIT License
1.01k stars 408 forks source link

Empty the field if nothing matches #673

Closed HugoWeb23 closed 3 years ago

HugoWeb23 commented 3 years ago

Hello,

Is it possible to add a prop to allow the field to be emptied if nothing matches?

Because when you leave the field, you might think that Chicaco is selected when he is not.

https://user-images.githubusercontent.com/22978990/134816377-5bcc2cd7-8972-46a7-b442-37282bd515b7.mp4

The field should behave like this

https://user-images.githubusercontent.com/22978990/134816547-8aae3a19-6af1-456b-9055-6f02aac62d2f.mp4

Thanks.

ericgio commented 3 years ago

Hi @HugoWeb23, thanks for the feature request! What you want is already possible using the clear method inside onBlur:

<Typeahead
  ...
  onBlur={() => {
    if (!selected.length) {
      typeaheadRef.current.clear();
    }
  }}
  ref={typeaheadRef}
/>

Try it out: https://codesandbox.io/s/rbt-673-clear-invalid-values-2kmil

HugoWeb23 commented 3 years ago

Thank you for your reply.

With only one field it works well but with an array of fields it gets complicated. (I am using react-hook-form)

I find that this should be the default behavior or let the developer choose whether or not to implement it via props.

ericgio commented 3 years ago

With only one field it works well but with an array of fields it gets complicated. (I am using react-hook-form)

I'm not familiar with react-hook-form, but it should be pretty trivial to create a wrapper component that adds the onBlur behavior and can be used as needed.

let the developer choose whether or not to implement it via props

Adding specific behaviors to the library along with props to enable or disable them out of the box is simply not scalable. My goal with this library is to provide basic behaviors out of the box as well as the flexibility for developers to implement any other behaviors they need.

saivivek116 commented 2 years ago

@ericgio The above logic you have mentioned in the onBlur method will not work in the case of multi-select can you suggest an alternative solution in that case?

ericgio commented 2 years ago

@saivivek116 that's right, using the clear method won't work for multi-select instances since it will clear the selections as well as the text. Unfortunately, there's also no API for controlling the input's value (#266). One workaround would be to save the selections using state, and update the typeahead's react key on blur. This would maintain the selections but cause the component to unmount and remount, clearing the text.