Use “onLayout” prop for a View
Measure component
import React from 'react'; import { View } from 'react-native'; export type TViewLayout = { height: number | null; width: number | null; x: number | null; y: number | null; }; interface Props { setViewMeasure: (data: TViewLayout) => void; } const MeasureView: React.FC<Props> = ({ children, setViewMeasure }) => { const onMeasureViewSize = (e: { nativeEvent: { layout: { height: number; width: number; x: number; y: number }; }; }) => { setViewMeasure(e.nativeEvent.layout); }; return <View onLayout={onMeasureViewSize}>{children}</View>; }; export default MeasureView;
Usage
function MeasureAButton() { const [measurement, setMeasurement] = React.useState<TViewLayout>({ height: null, width: null, x: null, y: null, }); return ( <> <MeasureView setViewMeasure={setMeasurement}> <Button /> </MeasureView> <Text>{measurement?.height}</Text> <Text>{measurement?.width}</Text> <Text>{measurement?.x}</Text> <Text>{measurement?.y}</Text> </> ); }
Leave a Reply