Answer the question
In order to leave comments, you need to log in
Why doesn't the resize event fire?
import React from 'react';
class Menu extends React.Component {
constructor() {
super();
this.state = {
height: window.innerHeight,
width: window.innerWidth,
}
this.updateDimensions = () => {
this.setState({
height: window.innerHeight,
width: window.innerWidth
});
}
}
componentDidMount() {
window.addEventListener("resize", this.updateDimensions);
console.log('тут')
}
componentWillUnmount() {
console.log('тут1')
window.removeEventListener("resize", this.updateDimensions);
}
render() {
return(
<div></div>
)
}
}
export default Menu;
componentDidMount() {
window.addEventListener("resize", this.updateDimensions);
console.log('тут')
}
Answer the question
In order to leave comments, you need to log in
Events don't fire. None and never. Event handlers fire.
So, the first one is great. And what is the second one? It's which one in componentWillUnmount? Well, that doesn't work right. When the component is removed from the DOM, then it will work. Or are you waiting for the first one to work again? - if so, then this is absurd.
Everything works as it should. You will render the width and height properties in render - you will see that they change when the window is resized (or move console.log to updateDimensions).
You can write a custom hook
import React, {useEffect, useState} from 'react';
export const useWindowSize = () => {
const [size, setSize] = useState([window.innerWidth, window.innerHeight])
const handleResize = () => {
setSize([window.innerWidth, window.innerHeight])
}
useEffect(() => {
window.addEventListener('resize', handleResize)
return () => window.removeEventListener('resize', handleResize)
}, [size])
return size
}
const [width, height] = useWindowSize()
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question