primereact icon indicating copy to clipboard operation
primereact copied to clipboard

Autocomplete: autoHighlight not working on option groups

Open GiovannaMonti opened this issue 4 months ago • 0 comments

Describe the bug

The autoHighlight prop is not working on an Autocomplete component with option groups. I feel like this is a bug, and not an intended behavior in case of grouped options.

I investigated a bit and found out that autoHighlight basically does this

DomHandler.addClass(itemToHighlight, 'p-highlight')
itemToHighlight.setAttribute('data-p-highlight', 'true')

on the ul's first child, which is the group header in case of grouped options. The result is that you don't get the autohighlight style on the first option, and you cannot press Enter to choose it.

I found a workaround for the style, by creating a custom onShow method that uses a ref to the Autocomplete component to retrieve the panel and its children.

  const onShow = () => {
    const panelElement = autocompleteRef.current?.getOverlay()
    if (panelElement) {
      const itemsWrapper = panelElement.firstChild
      const list = itemsWrapper?.firstChild

      let itemToHighlight: HTMLElement | null = null
      if (list && list instanceof Element) {
        for (const child of list.children) {
          if (child.classList.contains('p-autocomplete-item')) {
            itemToHighlight = child as HTMLElement
            break
          }
        }
      }

      if (itemToHighlight) {
        DomHandler.addClass(itemToHighlight, 'p-highlight')
        itemToHighlight.setAttribute('data-p-highlight', 'true')
      }
    }
  }

However, pressing Enter still won't work. I stopped there because I didn't have that much time to invest in this :)

Hope this'll get fixed Thanks!

Reproducer

No response

System Information

npmPackages:
    primereact: ^10.8.5 => 10.8.5 
    react: ^18.3.1 => 18.3.1

Steps to reproduce the behavior

  • Create an instance of the Autocomplete component with grouped options and autoHighlight prop
  • The first option in the first group does not get highlighted on panel open

Expected behavior

The first group option should be highlighted and be selected on Enter

GiovannaMonti avatar Aug 26 '25 13:08 GiovannaMonti