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

140
Visualizações
Hide after setInterval in react

I am trying to build a bar which appears after each 20 seconds and disappear after 5 seconds. It's working but often gives me error that classname in document.querySelector(".The_Bar").className = "The_Bar"; doesn't exist. So, is there any way to improvise this?

const Bar = () => {


  React.useEffect(() => {   
    const BarInterval = setInterval(() => {
      document.querySelector(".The_Bar").className = "The_Bar The_Bar_Show";
      const BarTimeout = setTimeout(() => {
        document.querySelector(".The_Bar").className = "The_Bar";
      }, 5000);
      return () => {
        clearTimeout(BarTimeout);
      };
    }, 20000);
    return () => {
      clearInterval(BarInterval);
      setNumber({});
    };
  }, [])

  
  return (
    <div className="The_Bar">
      <div className="Text">You viewing this page</div>
    </div>
  );
}
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

First,Why do you use document.querySelector(".The_Bar").className in react?

For this you have useRef.

Second, if you want to dispaly and then remove a div, you can useState to change dynamically. this way you control the class using react hooks which more easy and "clean"

const Bar = () => {
const [showBar,setShowBar] = useState(false)

  React.useEffect(() => {   
    const BarInterval = setInterval(() => {
     setShowBar(true)
      const BarTimeout = setTimeout(() => {
     setShowBar(false)
      }, 5000);
      return () => {
        clearTimeout(BarTimeout);
      };
    }, 20000);
    return () => {
      clearInterval(BarInterval);
      setNumber({});
    };
  }, [])

  
  return (
   <div className={showBar ? "The_Bar The_Bar_Show" : "No_Bar"}>
      <div className="Text">You viewing this page</div>
    </div>
  );
}

No_Bar style :

{
display:none;
}
about 4 years ago · Juan Pablo Isaza Relatório

0

You should not use such imperative approach to manipulate DOM when using React, try to achieve the same behaviour in a declarative way:

const Bar = () => {
  const [show, setShow] = useState(false);

  React.useEffect(() => {
    let interval;
    let timeout;

    interval = setInterval(() => {
      setShow(true);
      timeout = setTimeout(() => {
        setShow(false);
      }, 1000);
    }, 5000);
    return () => {
      clearInterval(interval);
      clearTimeout(timeout);
    };
  }, []);

  return (
    show && (
      <div className="The_Bar">
        <div className="Text">You viewing this page</div>
      </div>
    )
  );
};

Demo https://stackblitz.com/edit/react-ehwj9c

Selecting DOM elements with selectors in React is never a good idea, React makes use of a Virtual DOM to paint DOM and makes it asynchronously, so you may face all soort of bugs and misbehaviours by mixing imperative vanilla code with React code. You could use refs to access DOM nodes, but that also should be done very carefully. Instead of imperatively toggling a class as you would do in Vanilla JS, just toggle a React state, and use that state to declaratively toggle a view, or toggle a className, since React State triggers a re-render, this ensures that everything happens at the right pace.

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