Create React Native elements which do not respond to touch events: pointerEvents
The Context
For a React Native application, we wanted to create a “TikTok-style” social feed screen, which the user can scroll both vertically and horizontally (snap scrolling). Scroll vertically for the next post; scroll horizontally between different images in the same post.
We wanted to place a semi-transparent “overlay” containing the image description above the background image. When you scroll left and right on the overlay, it stays fixed and the background image moves behind it.
The Problem
When scrolling horizontally between images, gestures would hit the overlay (which needed to stay fixed) and not the background image (which we wanted to move) - horizontal scrolling did not work. Visually, the overlay needed to stay above the image, but we wanted the gestures to be captured by the images behind it.
The Solution
There’s a prop called
pointerEvents
to do this:pointerEvents="none"
prevents the gesture capture on the element and all its children;pointerEvents"box-only"
prevents the gesture capture on only that element.If you want to make several children “invisible” to touch gestures, you need the prop on all child elements.
The Code
<Element pointerEvents="none"/> <!-- You CAN'T touch this --> <Element pointerEvents="box-only"/> <!-- You CAN'T touch this --> <Element pointerEvents="none"> <!-- You can't touch this --> <Child /> <!-- You CAN'T touch this --> <Child /> <!-- You CAN'T touch this --> </Element> <Element pointerEvents="box-only"> <!-- You can't touch this --> <Child /> <!-- You CAN touch this --> <Child /> <!-- You CAN touch this --> </Element>