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';
}
}
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.