Home > database >  Get element by position (X and Y) in react-native
Get element by position (X and Y) in react-native

Time:08-24

On web, you can get any element by its position:

document.elementFromPoint(x, y)

Is there something similar in React Native? Can it be done with a native bridge (Java/Objective C)?

I would like to get an element on screen by position X and Y (Ignoring empty places and following transformation or styling calculations like padding, margin, borderRadius) then set it a native prop or dispatch events.

CodePudding user response:

You can use onLayout prop of React Native components. You should check this link

CodePudding user response:

Yes you can get your current elemnts position like in. 2 ways,

  1. onLayout
  2. suppose on click of that element you want to know that location

assign a ref to that

const newRef = useRef();

onButtonPress = () => {

newRef?.current?.measureInWindow( (fx, fy, width, height, px, py) => {
            console.log('Component width is: '   width)
            console.log('Component height is: '   height)
            console.log('X offset to frame: '   fx)
            console.log('Y offset to frame: '   fy)
            console.log('X offset to page: '   px)
            console.log('Y offset to page: '   py)

           
        })        

}



const onLayout=(event)=> {
    const {x, y, height, width} = event.nativeEvent.layout;
    
  }


return(
<TouchableOpacity ref={useRef} onLayout={onLayout} onPress={onButtonPress} >

</TouchableOpacity>
)
  • Related