reactjsaddeventlistenerhashchange

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.


Solution

  • 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 )
    });