maki
maki

Reputation: 621

how to make a react component state change on window resize?

I have a sidebar with a canvas animation which is created based on the size of the window.

componentDidMount() {
    let styles = window.getComputedStyle(this.sidebar.current)
    let w = styles.width
    let h = styles.height
    console.log("getComputedStyle:", styles.height, styles.width)
    this.setState({ "isOn": true, "height": h, "width": w })
}

My question is how could the state change according to window size change? I am trying to add a window.onresize function, but I don't know how to pass the component and states.

Upvotes: 0

Views: 1064

Answers (2)

Amila Senadheera
Amila Senadheera

Reputation: 13225

If you meant to calculate the navbar width and height when the screen resizes then the better option is to use getBoundingClientRect instead of getComputedStyle.

Following would also work

  onWindowResize = () => {
    const { current: navElement } = this.sidebar;
    if (navElement) {
      let rect = navElement.getBoundingClientRect();
      this.setState({
        height: rect.width,
        width: rect.height
      });
    }
  };

  componentDidMount() {
    this.onWindowResize();
    window.addEventListener("resize", this.onWindowResize);
  }

  componentWillUnmount() {
    window.removeEventListener("resize", this.onWindowResize);
  }

Code Sandbox

Upvotes: 1

MrFrenzoid
MrFrenzoid

Reputation: 1326

So, something like this?

You can create a function to handle the resize, and then hook that function to the resize event, also grabbing the height and width from window.

Also, don't forget to clean up the event if the component will be unmounted.

componentDidMount() {
    let styles = window.getComputedStyle(this.sidebar.current)
    let w = styles.width
    let h = styles.height
    console.log("getComputedStyle:", styles.height, styles.width)
    this.setState({ "isOn": true, "height": h, "width": w })
    
    let resizeHandler = () => {
      this.setState({ "isOn": this.state.isOn, "height": window.innerHeight, "width": window.innerWidth });
    }
    
    window.addEventListener('resize', resizeHandler);
}

componentWillUnmount() {
    window.removeEventListener('resize', resizeHandler);
}

Upvotes: 2

Related Questions