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

238
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
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