GithubHelp home page GithubHelp logo

zhbhun / react-native-intersection-observer Goto Github PK

View Code? Open in Web Editor NEW
88.0 5.0 12.0 387 KB

React Native component that monitors when an element enters or leaves the client viewport.

License: MIT License

JavaScript 20.22% Starlark 0.89% Java 22.97% Ruby 1.94% Objective-C 3.59% TypeScript 32.33% Makefile 2.29% C++ 10.35% Objective-C++ 5.41%
react react-native lazy-loading lazyload lazyload-images intersection-observer

react-native-intersection-observer's Introduction

react-native-intersection-observer

React Native implementation of the Intersection Observer API to tell you when an element enters or leaves the viewport.

Installation

Install using Yarn:

yarn add react-native-intersection-observer

or NPM:

npm install react-native-intersection-observer --save

Usage

You can pass any component to the <InView />, and it will handle creating the wrapping View component. Add a handler to the onChange method, and control the state in your own component. Any extra props you add to <InView> will be passed to the View component, allowing you to set the style, etc.

import React, { useRef } from 'react';
import { Text } from 'react-native';
import {
  IOScrollView,
  IOScrollViewController,
  InView,
} from 'react-native-intersection-observer';

function Demo() {
  const scrollViewRef = useRef<IOScrollViewController>(null);
  return (
    <IOScrollView ref={scrollViewRef}>
      <Text
        onPress={() => {
          scrollViewRef.current?.scrollToEnd();
        }}
      >
        Scroll to bottom
      </Text>
      <InView onChange={(inView: boolean) => console.log('Inview:', inView)}>
        <Text>
          Plain children are always rendered. Use onChange to monitor state.
        </Text>
      </InView>
    </IOScrollView>
  );
}

export default Demo;

Please note that the functionality of the InView component is dependent on the use of the withIO higher-order component to wrap your scrollable component. The react-native-intersection-observer library presently offers two frequently used scrollable components: IOScrollView and IOFlatList. It's imperative to utilize the InView component within one of these two components for it to work as intended. If neither IOScrollView nor IOFlatList suits your requirements, you have the flexibility to employ withIO to encapsulate your custom scrollable components.

// IOScrollView definition
import { ForwardRefExoticComponent, RefAttributes } from 'react';
import { ScrollView, ScrollViewProps } from 'react-native';
import { type IOComponentProps, withIO } from 'react-native-intersection-observer';

export type IOScrollViewController = ScrollView;

export type IOScrollViewProps = IOComponentProps & ScrollViewProps;

const IOScrollView = withIO(ScrollView, [
  'scrollTo',
  'scrollToEnd',
  'getScrollResponder',
  'getScrollableNode',
  'getInnerViewNode',
]);

export default IOScrollView as unknown as ForwardRefExoticComponent<
  IOScrollViewProps & RefAttributes<IOScrollViewController>
>;

Furthermore, InView cannot be used within nested scrollable components. It solely monitors the immediate parent's scroll behavior, and scrolling at higher ancestral levels does not trigger InView's visibility callback.

API

IOScrollView

IOFlatList Props

  • Props: Inherits FlatList Props

    Name Type Default Required Description
    rootMargin { top: number; left: number; right: number; bottom: number } undefined false root margin
  • Methods: Inherits FlatList Methods

InView Props

The <InView /> component also accepts the following props:

Name Type Default Required Description
as ComponentType View false Render the wrapping element as this element. Defaults to View.
children ReactNode true Children expects a plain child, to have the <InView /> deal with the wrapping element.
triggerOnce boolean false false Only trigger this method once
onChange (inView: boolean) => void false Call this function whenever the in view state changes. It will receive the inView boolean, alongside the current IntersectionObserverEntry.

License

react-native-intersection-observer is MIT licensed.

react-native-intersection-observer's People

Contributors

darkharry avatar zhbhun avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

react-native-intersection-observer's Issues

Adding a license

Is it possible to add a license file for this package? My companies automated ingestion process requires a LICENSE.md file.

I could send a pull request, if you can let me know the type of license for this package.

Thanks for this great package!

Documentation: improve readme

It would be useful to indicate in Readme file that parent context (IOFlatList or IOScrollView) is mandatory to make the library working, maybe introduce withIO hook would be usefull

Hard transition using RefreshControl in IOFlatlist

Hi,

We're using the IOFlatlist component to track Banner views in our FlatList components. These lists can be manually refreshed using the RefreshControl which is available in the regular FlatList component.

Unfortunately, today we found out that if the refreshing value returns to FALSE, there is no smooth transition. Instead, there's a hard "refresh" and all list items jumping back to the top. This seems no issue using the IOScrollView component. Is this a known issue and is there a solution for this?

I think this is also related to the component "remounts" every time a state value changes, as I also mentioned in #9.

const IOFlatlist = withIO(FlatList);

return (
   <IOFlatlist
      // @ts-ignore
      data={data}
      renderItem={({item, index}) => { ... }}
      style={styles.container}
      refreshControl={
        <RefreshControl
          refreshing={isLoading}
          onRefresh={async () => {
            await setIsLoading(true);
            await dispatch(getNews());
            await setIsLoading(false);
          }}
          colors={Colors.REFRESH_CONTROL_ANDROID}
          tintColor={Colors.REFRESH_CONTROL_IOS}
        />
      }
    />

Thanks in advance!

Kind regard,
Geert van Soest

Implement with Flatlist

Hi, first of all, awesome component!

I have a question. Would it be possible to implement this with a Flatlist instead? Thanks!

Warning "key is not a prop" after using IOFlatlist

Hi,

For tracking banner views and clicks I recently added this package to observe some of the FlatList components in our app. However everything seems to work fine, since I added the package I receive this warning in the console after some props are changing (e.g. after filtering):

Warning: PickerItem: key is not a prop. Trying to access it will result in undefined being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://reactjs.org/link/special-props)

I know the warning is triggered by another component inside IOFlatList, but I don't receive it when I replace IOFlatlist with FlatList. I found out the problem is the FilterSelect, which is in the ListHeaderComponent property, is remounted on each change using the IOFlatlist component. This isn't using the regular FlatList component.

Is there probably a way to prevent these components are remounted on every change using the IOFlatlist?

The FlatList component:

[...]

const ListNews = (props: Props) => {
  const dispatch = useAppDispatch();
  const [isLoading, setIsLoading] = useState(false);
  const [activeCategory, setActiveCategory] = useState('');
  const activeCategoryItems = props.items
    ? props.items[activeCategory] ?? props.items['all']
    : [];

  useMountEffect(() => {
    dispatch(getNews());
  });

  const IOFlatlist = withIO(FlatList);

  return (
    <IOFlatlist
      // @ts-ignore
      data={activeCategoryItems}
      ListHeaderComponent={
        props.categories && (
          <View style={styles.headerContainer}>
            <FilterSelect
              options={mapDataToFormSelectOptions(Object.values(props.categories), 'id', 'title')}
              activeOption={activeCategory}
              setActiveOption={setActiveCategory}
            />
          </View>
        )
      }

[...]

The filter component:

import SelectPicker from 'react-native-form-select-picker';

[...]

export type Props = {
  options: Array<TypeFormSelectOption>;
  activeOption: any;
  setActiveOption: Function;
};

const FilterSelect = (props: Props) => (
  <View style={styles.container}>
    <SelectPicker
      style={styles.input}
      placeholder={'Alles weergeven'}
      placeholderStyle={styles.text}
      selected={props.activeOption}
      onSelectedStyle={styles.text}
      onValueChange={value => {
        props.setActiveOption(value);
      }}>
      {Object.values(props.options).map((option, index) => (
        <SelectPicker.Item
          key={index}
          value={option.value}
          label={option.label}
        />
      ))}
    </SelectPicker>

[...]

Thanks in advance!

Kind regard,
Geert van Soest

Excessive callback on large list of components (+600)

Your package is causing error on reactnative "excessive number of pending callbacks" when it's loaded on +600 components list.

Please report: Excessive number of pending callbacks: 501. Some pending callbacks that might have leaked by never being called from native code: {"269138":{"module":"NativeAnimatedModule","method":"startAnimatingNode"},"269196":{},"269197":{},"269198":{},"269199":{},"269200":{},"269201":{},"269202":{},"269203":{},"269204":{},"269205":{},"269206":{},"269207":{},"269208":{},"269209":{},"269210":{},"269211":{},"269212":{},"269213":{},"269214":{},"269215":{},"269216":{},"269217":{},"269218":{},"269219":{},"269220":{},"269221":{},"269222":{},"269223":{},"269224":{},"269225":{},"269226":{},"269227":{},"269228":{},"269229":{},"269230":{},"269231":{},"269232":{},"269233":{},"269234":{},"269235":{},"269236":{},"269237":{},"269238":{},"269239":{},"269240":{},"269241":{},"269242":{},"269243":{},"269244":{},"...(truncated keys)...":451}

Issue on Android rendering children

Hey there @zhbhun I am having an issue where the children wrapped in the InView for Android arent rendering though it is working as expected for iOS. I am on "react-native": "0.66.4". I'm happy to provide any other information you may think is relevant. I appreciate your help. Here is what the code snippet looks like:

<IOScrollView style={styles.container}>
      <View style={styles.contentContainer}>
        {notificationCards.length ? (
          notificationCards?.map((item: ExtendedContentCard) => {
            return (
              <InView
                key={item.id}
                onChange={(inView: boolean) => {
                  if (inView && !beenViewed.includes(item.id)) {
                    setBeenViewed((current) => [...current, item.id]);
                    Braze.logContentCardImpression(item.id);
                  }
                }}>
                <NotificationCard
                  onPress={getCards}
                  key={item.id}
                  id={item.id}
                  title={item.title}
                  description={item.cardDescription}
                  image={item.image}
                  clicked={item.clicked}
                  ctaTitle={item.domain}
                  url={item.url}
                />
              </InView>
            );
          })
        ) : (
          <View style={styles.emptyState}>
            <Svg.EmptyNotificationState />
            <BodyRegular style={styles.emptyDesc}>
              {translate('notificationsPage.emptyState')}
            </BodyRegular>
          </View>
        )}
      </View>
    </IOScrollView>
  );
}

Screen Shot 2022-10-07 at 8 25 34 AM

Manage the threshold

Hello,

Firstly, your lib is very practical.

Do you think you can make it evolve to be able to manage the
threshold in addition to the rootMargin?

Thanks by advance

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.