Skip to content

Instantly share code, notes, and snippets.

@Landerson352
Created September 15, 2019 16:50
Show Gist options
  • Save Landerson352/ed8d6cbc495ff5ad138bb5a8a3ed7f20 to your computer and use it in GitHub Desktop.
Save Landerson352/ed8d6cbc495ff5ad138bb5a8a3ed7f20 to your computer and use it in GitHub Desktop.
A React Native HoC for measuring an element.
import React from 'react';
import { compose, lifecycle, withProps, withPropsOnChange, withStateHandlers } from 'recompose';
export default compose(
withProps(() => ({
measureRef: React.createRef(),
})),
withPropsOnChange(['measureRef'], ({ measureRef }) => ({
elementToMeasure: {
ref: measureRef,
collapsable: false, // for Android to return values other than `undefined`
},
})),
withStateHandlers({ fx: 0, fy: 0, width: 0, height: 0, px: 0, py: 0 }, {
handleMeasure: () => (fx, fy, width, height, px, py) => {
return {
fx,
fy,
width,
height,
px,
py,
isLayoutReady: true,
};
},
}),
lifecycle({
componentDidMount() {
const { handleMeasure, measureRef } = this.props;
this._isMounted = true;
// SetTimeout is often needed to give the UI thread a chance to catch up
// Other wise you may get all zeros as a result
setTimeout(() => {
if (measureRef.current && measureRef.current.measure) {
measureRef.current.measure((fx, fy, width, height, px, py) => {
if (this._isMounted) {
handleMeasure(fx, fy, width, height, px, py);
}
});
}
}, 0);
},
componentWillUnmount() {
this._isMounted = false;
},
}),
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment