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

228
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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