@applicaster/zapp-react-native-ui-components
Version:
Applicaster Zapp React Native ui components for the Quick Brick App
49 lines (37 loc) • 2.22 kB
Markdown
# /zapp-react-native-ui-components/Viewport
This module contains components to allow React Native components to update their behaviour depending on wether or not they are in the viewport
It comes in 3 parts:
- ViewportTracker: provides a starting point in the component tree from where other components can be measured and tracked
- ViewportAware: React Component which provides features to know whether its children are in the viewport or not
- ViewportEvents: Context and Event manager to know when components enter in the viewport or leave it
In most scenarios, you wouldn't need to use the third part directly.
## How to use them
First, you need to have a `ViewportTracker` component in your react tree. The first children needs to be a React Native primitive which responds to `onScroll`, `onLayout` and `onContentSizeChange` events. This means either a [ScrollView](https://reactnative.dev/docs/scrollview), a [Flatlist](https://reactnative.dev/docs/flatlist) or a [SectionList](https://reactnative.dev/docs/sectionlist)
```jsx
import * as React from "react";
import { ViewportTracker } from "@applicaster/zapp-react-native-ui-components/Components/Viewport";
export function App({ children }) {
return (
<ViewportTracker>
<ScrollView>{children}</ScrollView>
</ViewportTracker>
);
}
```
Then, on the components you want to track, you need to use the `ViewportAware` component and implement the logic you want when the component enters or leaves the boundaries of the ScrollView defined below your `ViewportTracker` - a good place to start being using a `inViewport` state variable.
```jsx
import * as React from "react";
import { ViewportAware } from "@applicaster/zapp-react-native-ui-components/Components/Viewport";
export function MyTrackedComponent(props) {
const [inViewport, setInViewport] = React.useState(false);
return (
<ViewportAware
preTriggerRatio={0.3} // allows the functions below to fire before the component actually enters the viewport for a smoother behaviour
onViewportEnter={() => setInViewport(true)}
onViewportLeave={() => setInViewport(false)}
>
{/* rest of your component here */}
</ViewportAware>
);
}
```