Created
August 10, 2018 15:13
-
-
Save freddi301/415143708b207a33e57cb2992fcce8e2 to your computer and use it in GitHub Desktop.
Responsive React Component
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import * as React from "react"; | |
| type Pixels = number; | |
| interface Params { | |
| width: Pixels; | |
| height: Pixels; | |
| } | |
| export class WindowResizeListener extends React.Component< | |
| { | |
| onResize?(args: Params): void; | |
| render(args: Params): React.ReactNode; | |
| }, | |
| Params | |
| > { | |
| public state: Params = this.getParams(); | |
| public render() { | |
| const { render } = this.props; | |
| return render ? render(this.state) : null; | |
| } | |
| private onResize = () => { | |
| this.setState(this.getParams); | |
| const { onResize } = this.props; | |
| if (onResize) { | |
| onResize(this.getParams()); | |
| } | |
| }; | |
| public componentDidMount() { | |
| window.addEventListener("resize", this.onResize); | |
| } | |
| public componentWillUnmount() { | |
| window.removeEventListener("resize", this.onResize); | |
| } | |
| private getParams() { | |
| const width = window.innerWidth; | |
| const height = window.innerHeight; | |
| return { width, height }; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment