Skip to content

Instantly share code, notes, and snippets.

@janicduplessis
Created September 7, 2018 02:46
Show Gist options
  • Save janicduplessis/355bdf234aff2d664b4329bcc16ffec1 to your computer and use it in GitHub Desktop.
Save janicduplessis/355bdf234aff2d664b4329bcc16ffec1 to your computer and use it in GitHub Desktop.
// @flow
import * as React from 'react';
import { Dimensions as RNDimensions } from 'react-native';
import hoistStatics from 'hoist-non-react-statics';
export type Metrics = $ReadOnly<{|
width: number,
height: number,
|}>;
export type EdgeInsets = $ReadOnly<{|
left: number,
top: number,
right: number,
bottom: number,
|}>;
type Props = $ReadOnly<{|
children: (Metrics, EdgeInsets) => React.Node,
|}>;
type State = {
window: Metrics,
safeAreaInsets: EdgeInsets,
};
export default class Dimensions extends React.Component<Props, State> {
state = {
window: RNDimensions.get('window'),
safeAreaInsets: RNDimensions.get('safeAreaInsets'),
};
componentDidMount() {
RNDimensions.addEventListener('change', this._handleDimensionsChange);
}
componentWillUnmount() {
RNDimensions.removeEventListener('change', this._handleDimensionsChange);
}
_handleDimensionsChange = ({ window, safeAreaInsets }) => {
this.setState({ window, safeAreaInsets });
};
render() {
return this.props.children(this.state.window, this.state.safeAreaInsets);
}
}
export function withDimensions(Component: any): React.ComponentType<any> {
class WithDimensionsComponent extends React.Component<any> {
static displayName = `withDimensions(${Component.displayName ||
Component.name})`;
render() {
return (
<Dimensions>
{(dimensions, safeAreaInsets) => (
<Component
{...this.props}
dimensions={dimensions}
safeAreaInsets={safeAreaInsets}
/>
)}
</Dimensions>
);
}
}
return hoistStatics(WithDimensionsComponent, Component);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment