Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

222
Vistas
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
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda