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

158
Visualizações
Unable to toggle a component for a second time using event listeners

You can find the codesandbox here.

I have a component that does the following:

  1. Display an icon
  2. If the icon is clicked, then, in its place, show a search input.
  3. If the user clicks anywhere outside of the search input while it is showing, hide the search input and show the icon again instead.

The problem is that after you click the icon, the search input does show, and clicking anywhere outside of the search input shows the icon again. But if you click the icon again for a second time, the search input does not show.

I tried attaching a ref to the icon and evaluating if the event is contained when the icon is clicked, but that conditional statement did not help. How can I make sure that when I click on the icon for any additional times, that the input shows up again? Thanks!

import ReactDOM from "react-dom";
import "@elastic/eui/dist/eui_theme_amsterdam_light.css";
import React, { useEffect, useRef, useState } from "react";
import { EuiButtonIcon, EuiFieldText } from "@elastic/eui";

const App = () => {
  const [showSearch, setShowSearch] = useState(false);
  const searchInputRef = useRef(null);

  useEffect(() => {
    document.addEventListener(
      "click",
      (event) => handleClickOutside(event, showSearch),
      false
    );
  }, [showSearch]);

  useEffect(
    () => () => {
      document.removeEventListener(
        "click",
        (event) => handleClickOutside(event, false),
        false
      );
    },
    []
  );

  const handleClickOutside = (event, showSearch) => {
    if (
      searchInputRef.current &&
      !searchInputRef.current.contains(event.target) &&
      showSearch
    ) {
      setShowSearch(false);
    }
  };

  if (showSearch) {
    return (
      <EuiFieldText
        icon="search"
        placeholder="Sample Search Placeholder ..."
        inputRef={searchInputRef}
      />
    );
  }

  return (
    <EuiButtonIcon
      aria-label="button"
      iconType="search"
      iconSize="xxl"
      onClick={() => setShowSearch(true)}
    />
  );
};

export default App;
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

I think your approach was correct, all I changed were the useEffect functions.

I just removed the other useEffect function you used to remove the click event.

I also passed the once option to the event listener, so the event would be removed after being run once.

useEffect(() => {
  const handleClickOutside = () => document.addEventListener("click", ({ target }) => {
    if (searchInputRef.current?.contains(target) === false && showSearch === true) setShowSearch(false);
    else handleClickOutside();
  }, { once: true });

  handleClickOutside();
}, [showSearch]);

Edit dazziling-code

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