Skip to content
Advertisement

Achieve combobox behavior for react-bootstrap-typeahead

I’m trying to use the react-bootstrap-typeahead control but I’m struck trying to make it do what I want. I’ve actually got 2 of these on my page, one of which is doing a true async lookup, and one which I almost want to behave like a combobox.

What I’d like to be able to do is to select an item, then click the dropdown to change my mind and choose another item. However if you try this, when you expand the list again it’s automatically filtered to just the item you have selected.

For example if I use the basic example on the demo page, and select Alabama, clicking the input now only displays Alabama and none of the other choices. I’d like this to ideally return me to the full list (is this possible?).

enter image description here

Advertisement

Answer

Yes, it’s possible. The filterBy prop can take a custom function, allowing you to filter results however you want. So building off the example you linked to, you’d want to do something along these lines:

<Typeahead
  filterBy={(option, text) => {
    if (this.state.selected.length) {
      // Display all the options if there's a selection.
      return true;
    }
    // Otherwise filter on some criteria.
    return option.name.toLowerCase().indexOf(text.toLowerCase()) !== -1;
  }}
  labelKey="name"
  onChange={(selected) => this.setState({selected})}
  options={options}
  placeholder="Choose a state..."
  selected={this.state.selected}
/>

Update As of v3.0.0, the filterBy callback passes props instead of text:

(option, props) => {
  if (props.selected.length) {
    // Display all the options if there's a selection.
    return true;
  }
  // Otherwise filter on some criteria.
  return option.name.toLowerCase().indexOf(props.text.toLowerCase()) !== -1;
}
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement