Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

221
Visualizações
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 à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda