Skip to content

Latest commit

 

History

History
42 lines (30 loc) · 939 Bytes

listen-window-resize.md

File metadata and controls

42 lines (30 loc) · 939 Bytes

Below code snippet is for listening for window resize event in React. This is usually for tracking window width and adjust component width according.

Code:


class Example extends React.Component {
    constructor() {
        super()

        this.state = { 
            height: window.innerHeight, 
            width: window.innerWidth
        }

        this.updateDimensions = this.updateDimensions.bind(this)
    }

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

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

    updateDimensions() {
        this.setState({
            height: window.innerHeight, 
            width: window.innerWidth
        })
    }

    render() {
        return (...)
    }

}

source: React Example - Listening for window resize event