Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect if a view is visible in a viewport or window in react native?

Tags:

react-native

I want a similar feature just like react visibility sensor, but in react-native. I have a flat list with multiple items(each having different height). I want to detect whether a particular item(lets say 5th item) comes inside the view port and when it goes out

like image 857
Romit Kumar Avatar asked Jan 14 '19 11:01

Romit Kumar


People also ask

How do you check if view is visible on screen React Native?

You can use onViewableItemsChanged to check which viewableItems are on the screen.

How do you know if a component is in viewport React Native?

To check if an element is in the viewport in React. js: Set the ref prop on the element. Use the IntersectionObserver API to track if the element is intersecting.


2 Answers

You can use onViewableItemsChanged to check which viewableItems are on the screen.

Here's a dummy class example:

class Demo extends Component {
  constructor() {
    super();
    this.viewabilityConfig = {
      viewAreaCoveragePercentThreshold: 95
    }
  }
  onViewableItemsChanged = ({ viewableItems }) => {
    // viewableItems will show you what items are in view
  }
  render() {
    <FlatList
      ...
      onViewableItemsChanged={this.onViewableItemsChanged}
      viewabilityConfig={this.viewabilityConfig}
    />
  }
} 

You'll need to modify viewAreaCoveragePercentThreshold accordingly.

like image 174
Dan Avatar answered Oct 23 '22 18:10

Dan


You can use Viewport from '@skele/components' like this:

0. Install Skele Components: yarn add @skele/components or npm install @skele/components

1. Wrap your scrollable view with Viewport.Tracker

    import { Viewport } from '@skele/components'
    ...
    render() {
        return (
            <Viewport.Tracker>
                <ScrollView scrollEventThrottle={16}>
                    { this.props.children }
                </ScrollView>
            </Viewport.Tracker>
        );
    }

2. Make its child components Viewport.Aware

import { Image } from 'react-native'
import { Viewport } from '@skele/components'
...
const ViewportAwareImage = Viewport.Aware(Image)
...
render() {
    return (
        <ViewportAwareImage
            source={{ uri: 'https://facebook.github.io/react-native/img/header_logo.png' }}
            onViewportEnter={() => console.log('Entered!')}
            onViewportLeave={() => console.log('Left!')} 
        />
    );
}

for more info visite this link

like image 4
ehsaneha Avatar answered Oct 23 '22 17:10

ehsaneha