1

I'm trying a pretty easy thing with react, namely a display of the current browser width. It works just fine when loading the page, but it doesn't update on resizing for some reason, even though I appear to update the state... Help?

import React from "react";

class SmartBr extends React.Component {
  constructor() {
    super();
    this.state = {
      WindowWidth:
        window.innerWidth ||
        document.documentElement.clientWidth ||
        document.body.clientWidth,
      WindowHeight:
        window.innerHeight ||
        document.documentElement.clientHeight ||
        document.body.clientHeight
    };
  }

  updateDimensions() {
    this.setState = {
      WindowWidth:
        window.innerWidth ||
        document.documentElement.clientWidth ||
        document.body.clientWidth,
      WindowHeight:
        window.innerHeight ||
        document.documentElement.clientHeight ||
        document.body.clientHeight
    };
  }

  /**
   * Add event listener
   */
  componentDidMount() {
    this.updateDimensions();
    window.addEventListener("resize", this.updateDimensions.bind(this));
  }

  /**
   * Remove event listener
   */
  componentWillUnmount() {
    window.removeEventListener("resize", this.updateDimensions.bind(this));
  }

  render() {
    return <p>{this.state.WindowWidth}</p>;
  }
}

export default SmartBr;

1 Answer 1

3

setState outside of the constructor is a function you call, not an object you set to it, so you need to change your updateDimensions function to call the setState method, and not assign an object as you are doing now :)

updateDimensions() {
  this.setState({
    WindowWidth:
      window.innerWidth ||
      document.documentElement.clientWidth ||
      document.body.clientWidth,
    WindowHeight:
      window.innerHeight ||
      document.documentElement.clientHeight ||
      document.body.clientHeight
  });
}
1
  • What ice said. setState is a function not an object.
    – rimraf
    Commented Oct 23, 2017 at 23:13

Not the answer you're looking for? Browse other questions tagged or ask your own question.