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

230
Visualizações
What is the most intelligent way to close the Dropdown Menu on clicking outside of its scope?

I have created this simple Dropdown in React and everything works fine until I click outside the scope of the Dropdown. https://codesandbox.io/s/restless-fast-x2jhe8

I've added a min-height: 100vh property on the body, to replicate a full size page. Like I said, the functionality to close the Dropdown menu when we click anywhere in the page that is not the Dropdown, is not implemented yet. I am not sure how to handle this in the most elegant way. I tried something along the lines of adding an event listener on the body with useEffect and then checking if event.target has class dropdown, but it didn't perform as expected.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

I make this common hook in which I pass ref of that element and state which show or close modal

import { useEffect } from 'react';

function useOutsideClickManager(ref: React.RefObject<HTMLInputElement>, setIsOpen: React.Dispatch<React.SetStateAction<boolean>>) {
  useEffect(() => {
    function handleClickOutside(event: { target: EventTarget | Node | null }) {
      if (ref.current && !ref.current.contains(event.target as Node)) {
        setIsOpen(false);
      }
    }
    document.addEventListener('mousedown', handleClickOutside);
    return () => {
      document.removeEventListener('mousedown', handleClickOutside);
    };
  }, [ref, setIsOpen]);
}
export { useOutsideClickManager };
  const [isOpen, setIsOpen] = React.useState(false);
  const wrapperRef = useRef<HTMLInputElement>(null);
  useOutsideClickManager(wrapperRef, setIsOpen);
about 4 years ago · Juan Pablo Isaza Relatório
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