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

118
Visualizações
addEventListener in onclick firing onload

I'm currently trying to get a with an onclick function to fire only when clicked. But I'm noticing after it's clicked and then on page load, the function is firing again.

Once I click 'Previous', the page goes to '/test1' for a second, then instantly loads '/test'. Am I not using this eventListener correctly?

Note: '/test1' and '/test2' are in one react project and '/test' is in another. I cannot use history.push for this scenario.

Header.js

<div id="header-link">
    <strong id="header-copy"></strong>
</div>

Entry.js

function getLink(currentPage, history) {
    if(currentPage.name === 'test1') {
        document.getElementById("header-link").addEventListener("click", function(e){
            e.preventDefault();
            window.location.pathname = '/test'
        });
        document.getElementById("header-copy").innerHTML = 'Back';
    }
    if (currentPage.name === 'test2') {
        document.getElementById("header-link").addEventListener("click", function(){ 
        history.push('/test1') 
        });
        document.getElementById("header-copy").innerHTML = 'Previous';
    }
}
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You don't need to use addEventListener when onClick is enough.

import { useHistory } from "react-router-dom";

const Header = () => {
  let history = useHistory();
  return (
    <div
      onClick={() => {
        if (window.location.href.endsWith("/test")) {
          history.push("/");
        } else {
          window.location.pathname = "/test";
          //history.push("/test");
        }
      }}
    >
      Click me
    </div>
  );
};

But if you insists on using addEventListener you need to remove them.

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