import hoistNonReactStatics from 'hoist-non-react-statics'; import * as React from 'react'; import { LayoutChangeEvent, View, ViewProps } from 'react-native'; export interface IDimensionsProps extends ViewProps { width: number; height: number; remeasure: (e: LayoutChangeEvent) => void; } interface IForwardedRefProp { forwardedRef: React.Ref; } /** * @description * A HOC to provide width and height properties with actual dimensions for your component. * @author https://github.com/Greg-Bush * @date 2019-04-11 * @template TResultProps * @param {React.ComponentType} WrappedComponent */ export default function withDimensions( WrappedComponent: React.ComponentType, ) { class WithDimensions extends React.Component< TResultProps & IForwardedRefProp > { public static displayName = `withDimensions(${getDisplayName(WrappedComponent)})`; public state = { width: 0, height: 0, initialRender: false }; public render() { const { forwardedRef, ...props } = this.props; return ( this.state.initialRender ? ( {this.props.children} ) : ); } private measure = ({ nativeEvent: { layout: { width = 0, height = 0 } = {} } = {} }) => { this.setState({ width, height, initialRender: true }); } } hoistNonReactStatics(WithDimensions, WrappedComponent); return React.forwardRef((props, ref) => ({props.children})); } const getDisplayName = (WrappedComponent: React.ComponentType) => WrappedComponent.displayName || WrappedComponent.name || 'WrappedComponent';