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

106
Views
¿Cómo cerrar el menú desplegable usando el propio gancho useOnOutsideClick?

Enfrenté un problema con el menú desplegable de mi móvil. Me gustaría cerrar el menú desplegable haciendo clic fuera (en algún lugar, digamos en los títulos anteriores) de mi botón y elementos desplegables.

Este es mi ejemplo .

Menú

 const Menu = () => { const [isMobileNavOpen, setMobileNavState] = useState(false); const mobileNavRef = useRef(); useOnOutsideClick(mobileNavRef, () => { if (isMobileNavOpen) setMobileNavState(false); }); const toggleMobileNav = () => { setMobileNavState(!isMobileNavOpen); }; return ( <div> <div className="dropdown" ref={mobileNavRef}> <button className="dropdown-btn" onClick={toggleMobileNav} type="button" > DROPDOWN BUTTON </button> {isMobileNavOpen && ( <div className="dropdown-menu" onClick={() => setMobileNavState(false)} > <a className="dropdown-item" href="#"> Item1 </a> <a className="dropdown-item" href="#"> Item2 </a> </div> )} </div> </div> ); };

mi anzuelo useOnClickOutside

 export const useOnOutsideClick = (ref, callback) => { const handleClick = (e) => { if (ref.current && ref.current.contains(e.target)) { callback(); console.log("click"); } }; useEffect(() => { document.addEventListener("click", handleClick); return () => { document.removeEventListener("click", handleClick); }; }); };

Por favor acerca de cualquier ayuda!

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Voltee la lógica de contenido de su gancho useOutsideClick . Desea verificar si el evento de clic se originó fuera del elemento de destino al que está adjunta la referencia.

 const handleClick = (e) => { if (!ref.current?.contains(e.target)) { callback(); console.log("click"); } };

Edite cómo-cerrar-el-menú-desplegable-usando-su-propio-usoenfuerahaga clic-enganche

anzuelo entero

 export const useOnOutsideClick = (ref, callback) => { const handleClick = (e) => { if (!ref.current?.contains(e.target)) { callback(); console.log("click"); } }; useEffect(() => { document.addEventListener("click", handleClick); return () => { document.removeEventListener("click", handleClick); }; }); };
about 4 years ago · Juan Pablo Isaza Report
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!