Measuring the Layout
Sometimes, you need to measure the current layout to apply some changes to the overall layout or to make decisions and call some specific logic.
React Native provides some native methods to know what are the measurements of the views.
The best way to invoke those methods is in a useLayoutEffect
hook: this will give you the most recent values for those measurements and it will let you apply changes in the same frame when the measurements are computed.
Typical code will look like this:
function AComponent(children) {
const targetRef = React.useRef(null)
useLayoutEffect(() => {
targetRef.current?.measure(({measurements}) => {
//do something with the `measurements`
});
}, [ /* add dependencies here */]);
return (
<View ref={targetRef}>
{children}
<View />
);
}
The methods described here are available on most of the default components provided by React Native. However, they are not available on composite components that aren't directly backed by a native view. This will generally include most components that you define in your own app.
measure(callback)
Determines the location on screen (x
and y
), width
, and height
in the viewport of the given view. Returns the values via an async callback. If successful, the callback will be called with the following arguments:
x
: thex
coordinate of the origin (top-left corner) of the measured view in the viewport.y
: they
coordinate of the origin (top-left corner) of the measured view in the viewport.width
: thewidth
of the view.height
: theheight
of the view.pageX
: thex
coordinate of the view in the viewport (typically the the whole screen).pageY
: they
coordinate of the view in the viewport (typically the the whole screen).
Also the width
and height
returned by measure()
are the width
and height
of the component in the viewport.
measureInWindow(callback)
Determines the location (x
and y
) of the given view in the window and returns the values via an async callback. If the React root view is embedded in another native view, this will give you the absolute coordinates. If successful, the callback will be called with the following arguments:
x
: thex
coordinate of the view in the current window.y
: they
coordinate of the view in the current window.width
: thewidth
of the view.height
: theheight
of the view.