Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

68
Views
eventListener for hashChange

I am trying to add an event listener for my page in ReactJS. I have added it to componentDidMount(). But the is only triggered for the initial page load.

How can I get it trigger whenever there is a change in the address bar.

componentDidMount:function(){

        window.addEventListener("hashchange", console.log('hashchange1'));
        $(window).bind("hashchange", console.log('$ - hashchange'));
        window.onhashchange =  console.log('hashchange3');      
        ReactDOM.findDOMNode(this).addEventListener('hashChange',console.log('ReactDOM - hashchange'));
    },

I've tried several different ways to get it to work, but they all work only on the first load. What am I doing wrong?

Thanks.

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

You're just executing the console.log in every case, and adding its return value as the listener. You need to pass a function as an event listener, for example:

window.addEventListener("hashchange", e => console.log('hashchange1', window.location.hash ));

https://jsfiddle.net/ku6okrp2/

EDIT to make it look more obvious using ES5:

window.addEventListener("hashchange", function(e){ 
  console.log('hashchange1', window.location.hash )
});
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!