Skip to content
Advertisement

Document resize event is not working in javascript/react

I want to look for a resize event and then set the graph’s current width based upon widow width.

Below is the code that registers an event inside the useEffect

  useEffect(() => {
    let cb = function (e) {
      console.log('event happened');
      console.log('width: ', window.innerWidth);
      console.log('height', window.innerHeight);
    };
    // window.onresize = cb;
    document.addEventListener('resize', cb);
    return () => document.removeEventListener('resize', cb);
  }, []);

None of the above logs working. And if I use onresize to listen event it works. This is happening for Chrome as well for Mozilla.

What I am doing wrong here??

Advertisement

Answer

If you change document to window it works.

 useEffect(() => {
    let cb = function (e) {
      console.log('event happened');
      console.log('width: ', window.innerWidth);
      console.log('height', window.innerHeight);
    };
    // window.onresize = cb;
    window.addEventListener('resize', cb);
    return () => window.removeEventListener('resize', cb);
  }, []);

https://codesandbox.io/s/serene-mirzakhani-sd8hmz?file=/src/App.js

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement