How do you re-render a view when the browser is resized? in REACT

Practice



  1. You can listen for the

    resize
    event in
    componentDidMount()
    and then update the dimensions (
    width
    and
    height
    ). You should remove the listener in the
    componentWillUnmount()
    method.
    class WindowDimensions extends React.Component {
      constructor(props){
        super(props);
        this.updateDimensions = this.updateDimensions.bind(this);
      }
       
      componentWillMount() {
        this.updateDimensions()
      }
    
      componentDidMount() {
        window.addEventListener('resize', this.updateDimensions)
      }
    
      componentWillUnmount() {
        window.removeEventListener('resize', this.updateDimensions)
      }
    
      updateDimensions() {
        this.setState({width: window.innerWidth, height: window.innerHeight})
      }
    
      render() {
        return <span>{this.state.width} x {this.state.height}</span>
      }
    }

Comments

To leave a comment

If you have any suggestion, idea, thanks or comment, feel free to write. We really value feedback and are glad to hear your opinion.
To reply

Lectures and tutorial on "Scripting client side JavaScript, jqvery, BackBone"

Terms: Scripting client side JavaScript, jqvery, BackBone