Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Focus not returned to triggering button when closing modal #3320

Closed
eroltibern opened this issue Jun 24, 2024 · 1 comment · Fixed by #3365
Closed

Focus not returned to triggering button when closing modal #3320

eroltibern opened this issue Jun 24, 2024 · 1 comment · Fixed by #3365
Assignees

Comments

@eroltibern
Copy link

What package within Headless UI are you using?

@headlessui/react

What version of that package are you using?

v1.7.17 - v.2.x.x

What browser are you using?

Chrome

Reproduction URL

Sandbox

Describe your issue

When opening a Dialog by clicking on a button with its content wrapped in a span, focus is not properly restored to the triggering button after the dialog closes. Focus is instead returned to body.

<button onClick={open}>
  <span>Click me</span>
</button>

I believe this is due to the span element being added as the latest focused element in the active element history, and when trying to focus the span the browser falls back to focusing body instead.

A solution could be to find the first focusable element in the history array and trying to focus that? Something like this:

return useEvent(() => {
    return (
      localHistory.current.find(
        (x) => x != null && x.isConnected && x.matches(focusableSelector)
      ) ?? null
    )
  })

Here:

What do you think? I can open a PR if I'm not missing something important here.

@RobinMalfait
Copy link
Member

Hey thanks for the bug report, your idea is a good idea, but instead of checking if the element is the focusable element when figuring out the element to restore, I resolved the closest focusable element when recording the click instead.

This should be fixed by #3365, and will be available in the next release.

You can already try it using:

  • npm install @headlessui/react@insiders.
  • npm install @headlessui/vue@insiders.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants