jbmgil_vlrzz
jbmgil_vlrzz

Reputation: 105

React. Headless UI Menu Items can't receive focus on keyboard navigation

I have a dropdown menu builth with Headless UI Menu component, but the menu links inside this dropdown are not getting focused on keyboard navigation.

my code goes something like so:

function Dropdown(parent, children) {

    return (             
        <Menu as="div" className="Submenu">
            {
                ({close}) => (
                    <>
                        <Menu.Button>
                            { parent.label }
                        </Menu.Button>
                        <Menu.Items as="ul" className="subitems">
                            {
                                children.map(child => (
                                    <Menu.Item as="li" className="subitem" key={ child.id }>
                                        <Link href={ child.link }>
                                            {  child.label }
                                        </Link>                                    
                                    </Menu.Item>
                                ))
                            }
                        </Menu.Items>                    
                    </>
                )
            }
        </Menu>
    );
}

The only thing getting the focus is the <ul></ul that wraps the items, but once I press tab the dropdown closes and the focus goes to the next item on the parent level menu.

enter image description here

The final html rendered is this:

enter image description here

I've tried to add tabIndex={0} to the tags, but the output stays the same. I also tried to create a Link wrapper component ike suggested here, but it didn't work.

Upvotes: 2

Views: 1965

Answers (3)

sunny-mittal
sunny-mittal

Reputation: 509

For anyone else having this issue, I found that it happens if you use the as prop of Menu.Item. Removing that causes it to render a fragment and then the ref is passed properly. On this note, the child component of Menu.Item also must accept a ref, either by being a primitive element (i.e. button) or by using a custom component that forwards a ref to a primitive.

Upvotes: 0

Kraken
Kraken

Reputation: 5890

Use the popover. I ran into the same trouble with the menu, and the popover let's you tab into it.

Upvotes: 0

S L
S L

Reputation: 1

The main focus should stay on ul element, it's okay. But there is an internal focus that you can change using arrows, it's just now showing. You can test it by navigating using arrows and pressing enter. Links will work.

Upvotes: 0

Related Questions