Monitor React Native Component Visibility With The Viewport Detector Component

react-native-viewport-detector is a React Native library that allows you to easily monitor whether a child component is currently visible within the viewport.

By tracking visibility based on a percentage of the component’s width and height, it provides a straightforward API for determining if an element is on screen.

This makes it useful for various cases like lazy loading content, triggering animations, or detecting user interactions.

How to use it:

1. Install & import.

# Yarn
$ yarn react-native-viewport-detector
# NPM
$ npm i react-native-viewport-detector
import React, { useState } from "react";
import { SafeAreaView, ScrollView, StyleSheet, View } from "react-native";
import {
  ViewPortDetector,
  ViewPortDetectorProvider,
} from "react-native-viewport-detector";

2. The library offers a simple way to know when a React Native component enters or leaves the visible viewport. It exposes a ViewPortDetector component that can wrap any child element. By passing in a percentage threshold for the width and height, you can check if enough of the component is on screen to be considered “visible”.

function App(): JSX.Element {
  return (
    <SafeAreaView style={styles.container}>
      <View style={styles.header} />
      <ViewPortDetectorProvider flex={1}>
        <ScrollView>
          {Array.from({ length: 10 }).map((_, index) => (
            <ViewComponent key={`app_item_${index}`} />
          ))}
        </ScrollView>
      </ViewPortDetectorProvider>
    </SafeAreaView>
  );
}
function ViewComponent(): JSX.Element {
  const [inViewPort, setInViewPort] = useState(false);
  return (
    <ViewPortDetector
      onChange={setInViewPort}
      percentHeight={0.7}
      percentWidth={1}
      frequency={300}
    >
      <View style={[styles.item, inViewPort ? styles.inViewPort : undefined]} />
    </ViewPortDetector>
  );
}

Preview:

Monitor React Native Component Visibility With The Viewport Detector Component

Download Details:

Author: thinhkhang97

Live Demo: View The Demo

Download Link: Download The Source Code

Official Website: https://github.com/thinhkhang97/react-native-viewport-detector

License: MIT

Add Comment