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

124
Vistas
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 Respuestas
Responde la pregunta

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