I am working on a react native app and I want to handle touches on screen.
One use case is when the user "press" on screen, I want to be able to get the position (x,y) of a specific component on screen to know if it matches the (x,y) of the touch.
I've searched already on stack overflow, but none of the given solutions worked...
In my root component:
_onPress = () => {
// How can I get the position of my component ?
this._myComponent.xxx();
};
render() {
return (
<View><MyComponent ref={(r) => this._myComponent = r;} /></View>
);
}
EDIT: After trying this solution (React Native: Getting the position of an element) I made it work as follow:
In MyComponent.js:
getPosition () => {
this._ref._component.measure((width, height, px, py, fx, fy) => {
const location = {
fx: fx,
fy: fy,
px: px,
py: py,
width: width,
height: height
}
console.log(location)
});
};
render() {
return (
<View ref={(r) => { this._ref = r;} } />
);
}
Thanks for your help!
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
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)}
/>
);
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With