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
–
JavaScript
x
11
11
1
useEffect(() => {
2
let cb = function (e) {
3
console.log('event happened');
4
console.log('width: ', window.innerWidth);
5
console.log('height', window.innerHeight);
6
};
7
// window.onresize = cb;
8
document.addEventListener('resize', cb);
9
return () => document.removeEventListener('resize', cb);
10
}, []);
11
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.
JavaScript
1
11
11
1
useEffect(() => {
2
let cb = function (e) {
3
console.log('event happened');
4
console.log('width: ', window.innerWidth);
5
console.log('height', window.innerHeight);
6
};
7
// window.onresize = cb;
8
window.addEventListener('resize', cb);
9
return () => window.removeEventListener('resize', cb);
10
}, []);
11
https://codesandbox.io/s/serene-mirzakhani-sd8hmz?file=/src/App.js