Search code examples
reactjsreact-bootstrap-typeahead

Allow activeElement to be selected on mouse event


While trying to hover an item in the dropdown suggestions menu, I'm trying to make that item the activeElement and activeIndex. But the keyboard up/down arrow stops working with this change. I would like to have the up/down arrow key work as well from the activeIndex. How to do that? Here's the code i have

  public itemFocus = (e: any) => {
    let ce = e.currentTarget.id.toString();
    ce = ce.substring(ce.length - 1);
    this._typeahead.getInstance().setState({
      activeIndex: ce,
      activeItem: this.state.options[ce]});
  }

with idx denoting the iterator index of results

<MenuItem onMouseOver={this.itemFocus} key={idx} option={state} position={idx}>

Solution

  • You seem to be on the right track, though there are easier ways to get the index and data of the hovered item. The following should work:

    Note: The following solution is not officially supported by the API and could break without warning if the package internals change.

    <Typeahead
      options={[ ... ]}
      ref={(typeahead) => this._typeahead = typeahead}
      renderMenu={(filteredOptions, menuProps) => (
        <Menu {...menuProps}>
          {filteredOptions.map((option, index) => (
            <MenuItem
              onMouseOver={() => {
                this._typeahead.getInstance().setState({
                  activeIndex: index,
                  activeItem: option,
                });
              }}
              option={option}
              position={index}>
              {option}
            </MenuItem>
          ))}
        </Menu>
      )}
    />
    

    Working example: https://codesandbox.io/s/ojz4kzn2vq