Skip to content

Instantly share code, notes, and snippets.

@freddi301
Created August 10, 2018 15:13
Show Gist options
  • Select an option

  • Save freddi301/415143708b207a33e57cb2992fcce8e2 to your computer and use it in GitHub Desktop.

Select an option

Save freddi301/415143708b207a33e57cb2992fcce8e2 to your computer and use it in GitHub Desktop.
Responsive React Component
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