claudiopb
claudiopb

Reputation: 1090

React JS function to catch the browser's window resizing isn't working

Here is my component code. Everything is working successfully except this 'onResize' function.

 class MyComponent extends Component {
      constructor(props) {
        super(props)   
        this.onResize = this.onResize.bind(this)
      }

    onResize = () => {
        window.onresize = () => {
          alert(true)
          //I had tried with 'this.alert(true)' too
        }
      }
    }

    componentDidMount() {
        this.onResize()
      }

    //rest of the code ommited

Upvotes: 0

Views: 305

Answers (2)

varoons
varoons

Reputation: 3887

You need to add an event listener for the resize

onResize() {
  this.setState({
    width: $(window).width(), 
    height: $(window).height()
  })
}

componentWillMount() {
    this.onResize();
}

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

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

Upvotes: 0

0xc14m1z
0xc14m1z

Reputation: 3725

You have to add an event listener in the componentDidMount lifecycle:

componentDidMount() {
  window.addEventListener('resize', this.handleWindowResize)
}

Remember to remove the event listener when you unmount the component to avoid memory leaks:

componentWillUnmount() {
  window.removeEventListener('resize', this.handleWindowResize)
}

Upvotes: 2

Related Questions