How to get the position of a component on screen in react native?

React Native

You can use .measure():

this._myComponent._component.measure((width, height, px, py, fx, fy) => {
  // do positioning checks here
}

Determines the location on screen, width, and height of the given view and returns the values via an async callback. If successful, the callback will be called with the following arguments: x, y, width, height, pageX, pageY.

Docs: https://facebook.github.io/react-native/docs/direct-manipulation.html#other-native-methods


Web API (no React Native)

If you're working with a DOM node, you can use Element.getBoundingClientRect():

let domRect = this._myComponent.getBoundingClientRect();
let { x, y } = domRect;

The result is the smallest rectangle which contains the entire element, with read-only left, top, right, bottom, x, y, width, and height properties describing the overall border-box in pixels. Properties other than width and height are relative to the top-left of the viewport.

Docs: https://developer.mozilla.org/en-US/docs/Web/API/Element/getBoundingClientRect


For an example in a functional component using useRef in React Native:

const BoardSquare = props => {
  const squareRef = useRef(null);

  console.log('squareRef', squareRef);

  const doMeasure = square => {
    squareRef.current.measure((width, height, px, py, fx, fy) => {
      const location = {
        fx: fx,
        fy: fy,
        px: px,
        py: py,
        width: width,
        height: height,
      };
      console.log('location', location);
      square.x = fx;
      square.y = fy;
      square.xMax = fx + px;
      square.yMax = fy + py;
    });
  };

  return (
    <Square
      {...props}
      ref={squareRef}
      filled={props.square.filled}
      onLayout={() => doMeasure(props.square)}
    />
  );
};