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

227
Vistas
Dropdown menu in React js

I am currently building a dropdown based design in React. When I click any one of the buttons, the dropdown appears. Now when I click anywhere inside the dropdown, I want the dropdown to stay. But based on my current implementation, when I click on the dropdown, the dropdown goes away. I can fix this behaviour by prop drilling but the code gets ugly. How can I implement this cleanly?

export default function SearchFilter() {
  const [selected, setSelected] = useState(null);

  const handleClick = (e) => {
    const id = e.target.id;
    setSelected(id);
    }
  };
  const clearSelected = (e) => {
    if (e.target.id) return;
    setSelected(null);
  };
  useEffect(() => {
    window.addEventListener("click", clearSelected);
    return () => window.removeEventListener("click", clearSelected);
  });
  return (
    <div onClick={handleClick}>

      <MenuItem id={1} className={selected == 1 ? "shadow-xl" : ""}>

          <MenuDropdown className={`absolute left-0 top-full translate-y-3 ${
            selected != 1 && "hidden" />

      </MenuItem>

      <MenuItem id={2} className={selected == 2 ? "shadow-xl" : ""} />
      <MenuItem id={3} className={selected == 3 ? "shadow-xl" : ""} />
    </div>
  );
}
about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

I know of a fancy hook for clicking outside of something, will probably help out and I keep seeing it referred to for this, here: https://usehooks.com/useOnClickOutside/

about 4 years ago · Juan Pablo Isaza Denunciar

0

You shouldn't handle the close like that, you can't control where you click with that listener. You should use material ui components because the components have all these functions and many others that you didn't think of right now.

If you want to implement it yourself, you should add a ref to dropdown and create a hook for clicking outside the component.

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