skip to Main Content

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.

OBS: I’m not referring to onLayout property or any other declared in the component’s construction/render, my idea is from any X and Y position get an element that corresponds to these coordinates then get a reference to it. A use case for example: Create a virtual cursor that dispatch click events on correct components, following margin/padding and ignoring pointerEvents none.

Image Example

2

Answers


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

    Login or Signup to reply.
  2. 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>
    )
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search