Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

223
Views
HeadlessUI React, how to detect currently focused element?

I'm trying to build a funky use case:

I have a HeadlessUI dialog, inside this dialog, there is a HeadlessUI Menu component as a nested child, I want to trigger the menu via a keyboard shortcut

I have managed to trigger the dialog, via:

// I took the useWindowEvent from the headlessUI code
useWindowEvent("keydown", (event) => {
    if (event.key === "p") {
      event.preventDefault()
      event.stopPropagation()
      selectorRef.current?.click()
    }
  })

and on my Menu component:

// My react component forwardRefs to the trigger button
export const ProjectSelector = forwardRef(
... some other component code
<Menu.Button ref={ref} as="div">
... other code

This works fine to trigger the Menu, but the menu also has a search bar, so whenever I press the p key, the listener triggers again and programmatically closes the Menu

I have taken a look inside the headlessUI code trying to understand the focus trap code, but it's above my head, is there any way to detect if the parent Dialog has focus? that way I can just ignore the keypress if focus is on the menu :)

Workaround:

While writing the question I stumbled upon a workaround... it is not super pretty, so maybe someone can come up with a better solution:

  // I'm pretty sure I'm doing everything wrong in here
  // but I couldn't find another way to remotely trigger and keep focus on the menu component
  useWindowEvent("keydown", (event) => {
    if (
      event.key === "p" &&
      document.activeElement?.getAttribute("role") !== "menu" &&
      document.activeElement?.tagName !== "INPUT"
    ) {
      event.preventDefault()
      event.stopPropagation()
      selectorRef.current?.click()
    }
  })
about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!