U
U
uzi_no_uzi2019-08-30 17:24:49
JavaScript
uzi_no_uzi, 2019-08-30 17:24:49

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;

Tried to catch the window resize event. But for some reason only the first console.log();
componentDidMount() {
          window.addEventListener("resize", this.updateDimensions);
          console.log('тут')
     }

Why is this happening?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
0
0xD34F, 2019-08-30
@uzi_no_uzi

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).

A
AntonGre4ka, 2020-09-16
@AntonGre4ka

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
}

And in the component, use
const [width, height] = useWindowSize()

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question