From ba8d059b51fdab32cb59a810b636454c12f0b233 Mon Sep 17 00:00:00 2001 From: Daniel Schmidt Date: Mon, 25 Apr 2022 10:24:00 +0200 Subject: [PATCH] feat: support onChange on useInView --- README.md | 41 ++++++++++++++++++------------------ docs/Recipes.md | 27 +++++++++++++----------- src/__tests__/hooks.test.tsx | 17 +++++++++++++++ src/index.tsx | 5 ++--- src/stories/Hooks.story.tsx | 2 +- src/useInView.tsx | 6 ++++++ 6 files changed, 62 insertions(+), 36 deletions(-) diff --git a/README.md b/README.md index dd600211..4351dc62 100644 --- a/README.md +++ b/README.md @@ -2,8 +2,7 @@ [![Version Badge][npm-version-svg]][package-url] [![GZipped size][npm-minzip-svg]][bundlephobia-url] -[![Test][test-image]][test-url] -[![License][license-image]][license-url] +[![Test][test-image]][test-url] [![License][license-image]][license-url] [![Downloads][downloads-image]][downloads-url] React implementation of the @@ -22,11 +21,13 @@ to tell you when an element enters or leaves the viewport. Contains both a - โšก๏ธ **Optimized performance** - Reuses Intersection Observer instances where possible - โš™๏ธ **Matches native API** - Intuitive to use -- ๐Ÿ›  **Written in TypeScript** - It'll fit right into your existing TypeScript project +- ๐Ÿ›  **Written in TypeScript** - It'll fit right into your existing TypeScript + project - ๐Ÿงช **Ready to test** - Mocks the Intersection Observer for easy testing with [Jest](https://jestjs.io/) - ๐ŸŒณ **Tree-shakeable** - Only include the parts you use -- ๐Ÿ’ฅ **Tiny bundle** - Around __~1.15kB__ for `useInView` and __~1.6kB__ for `` +- ๐Ÿ’ฅ **Tiny bundle** - Around **~1.15kB** for `useInView` and **~1.6kB** for + `` ## Installation @@ -146,27 +147,27 @@ export default Component; Provide these as the options argument in the `useInView` hook or as props on the **``** component. -| Name | Type | Default | Required | Description | -| ---------------------- | ---------------------- | --------- | -------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| **root** | `Element` | document | false | The IntersectionObserver interface's read-only root property identifies the Element or Document whose bounds are treated as the bounding box of the viewport for the element which is the observer's target. If the root is `null`, then the bounds of the actual document viewport are used. | -| **rootMargin** | `string` | '0px' | false | Margin around the root. Can have values similar to the CSS margin property, e.g. "10px 20px 30px 40px" (top, right, bottom, left). | -| **threshold** | `number` \| `number[]` | 0 | false | Number between `0` and `1` indicating the percentage that should be visible before triggering. Can also be an array of numbers, to create multiple trigger points. | -| **trackVisibility** ๐Ÿงช | `boolean` | false | false | A boolean indicating whether this IntersectionObserver will track visibility changes on the target. | -| **delay** ๐Ÿงช | `number` | undefined | false | A number indicating the minimum delay in milliseconds between notifications from this observer for a given target. This must be set to at least `100` if `trackVisibility` is `true`. | -| **skip** | `boolean` | false | false | Skip creating the IntersectionObserver. You can use this to enable and disable the observer as needed. If `skip` is set while `inView`, the current state will still be kept. | -| **triggerOnce** | `boolean` | false | false | Only trigger the observer once. | -| **initialInView** | `boolean` | false | false | Set the initial value of the `inView` boolean. This can be used if you expect the element to be in the viewport to start with, and you want to trigger something when it leaves. | -| **fallbackInView** | `boolean` | undefined | false | If the `IntersectionObserver` API isn't available in the client, the default behavior is to throw an Error. You can set a specific fallback behavior, and the `inView` value will be set to this instead of failing. To set a global default, you can set it with the `defaultFallbackInView()` | +| Name | Type | Default | Required | Description | +| ---------------------- | ------------------------- | --------- | -------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| **root** | `Element` | document | false | The IntersectionObserver interface's read-only root property identifies the Element or Document whose bounds are treated as the bounding box of the viewport for the element which is the observer's target. If the root is `null`, then the bounds of the actual document viewport are used. | +| **rootMargin** | `string` | '0px' | false | Margin around the root. Can have values similar to the CSS margin property, e.g. "10px 20px 30px 40px" (top, right, bottom, left). | +| **threshold** | `number` or `number[]` | 0 | false | Number between `0` and `1` indicating the percentage that should be visible before triggering. Can also be an array of numbers, to create multiple trigger points. | +| **onChange** | `(inView, entry) => void` | undefined | false | Call this function whenever the in view state changes. It will receive the `inView` boolean, alongside the current `IntersectionObserverEntry`. | +| **trackVisibility** ๐Ÿงช | `boolean` | false | false | A boolean indicating whether this IntersectionObserver will track visibility changes on the target. | +| **delay** ๐Ÿงช | `number` | undefined | false | A number indicating the minimum delay in milliseconds between notifications from this observer for a given target. This must be set to at least `100` if `trackVisibility` is `true`. | +| **skip** | `boolean` | false | false | Skip creating the IntersectionObserver. You can use this to enable and disable the observer as needed. If `skip` is set while `inView`, the current state will still be kept. | +| **triggerOnce** | `boolean` | false | false | Only trigger the observer once. | +| **initialInView** | `boolean` | false | false | Set the initial value of the `inView` boolean. This can be used if you expect the element to be in the viewport to start with, and you want to trigger something when it leaves. | +| **fallbackInView** | `boolean` | undefined | false | If the `IntersectionObserver` API isn't available in the client, the default behavior is to throw an Error. You can set a specific fallback behavior, and the `inView` value will be set to this instead of failing. To set a global default, you can set it with the `defaultFallbackInView()` | ### InView Props The **``** component also accepts the following props: -| Name | Type | Default | Required | Description | -| ------------ | -------------------------------------------------------- | ------- | -------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| **as** | `string` | 'div' | false | Render the wrapping element as this element. Defaults to `div`. | -| **children** | `({ref, inView, entry}) => React.ReactNode`, `ReactNode` | | true | Children expects a function that receives an object containing the `inView` boolean and a `ref` that should be assigned to the element root. Alternatively pass a plain child, to have the `` deal with the wrapping element. You will also get the `IntersectionObserverEntry` as `entry, giving you more details. | -| **onChange** | `(inView, entry) => void` | | false | Call this function whenever the in view state changes. It will receive the `inView` boolean, alongside the current `IntersectionObserverEntry`. | +| Name | Type | Default | Required | Description | +| ------------ | ---------------------------------------------------- | --------- | -------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| **as** | `string` | 'div' | false | Render the wrapping element as this element. Defaults to `div`. | +| **children** | `({ref, inView, entry}) => ReactNode` or `ReactNode` | undefined | true | Children expects a function that receives an object containing the `inView` boolean and a `ref` that should be assigned to the element root. Alternatively pass a plain child, to have the `` deal with the wrapping element. You will also get the `IntersectionObserverEntry` as `entry, giving you more details. | ### IntersectionObserver v2 ๐Ÿงช diff --git a/docs/Recipes.md b/docs/Recipes.md index 438f3e7a..499f3ae8 100644 --- a/docs/Recipes.md +++ b/docs/Recipes.md @@ -91,18 +91,20 @@ for an IntersectionObserver. ```jsx import React from 'react'; import { useInView } from 'react-intersection-observer'; -import { motion } from 'framer-motion'; const LazyAnimation = () => { - const [ref, inView] = useInView({ + const { ref, inView } = useInView({ triggerOnce: true, rootMargin: '-100px 0px', }); return ( - +
๐Ÿ‘‹ - +
); }; @@ -121,22 +123,23 @@ fire an event on your tracking service. - Instead of `threshold`, you can use `rootMargin` to have a fixed amount be visible before triggering. Use a negative margin value, like `-100px 0px`, to have it go inwards. You can also use a percentage value, instead of pixels. +- You can use the `onChange` callback to trigger the tracking. ```jsx -import React, { useEffect } from 'react'; +import * as React from 'react'; import { useInView } from 'react-intersection-observer'; const TrackImpression = () => { - const [ref, inView] = useInView({ + const { ref } = useInView({ triggerOnce: true, rootMargin: '-100px 0', + onChange: (inView) => { + if (inView) { + // Fire a tracking event to your tracking service of choice. + dataLayer.push('Section shown'); // Here's a GTM dataLayer push + } + }, }); - useEffect(() => { - if (inView) { - // Fire a tracking event to your tracking service of choice. - dataLayer.push('Section shown'); // Here's a GTM dataLayer push - } - }, [inView]); return (
diff --git a/src/__tests__/hooks.test.tsx b/src/__tests__/hooks.test.tsx index f9c1435e..519e87d7 100644 --- a/src/__tests__/hooks.test.tsx +++ b/src/__tests__/hooks.test.tsx @@ -107,6 +107,23 @@ test('should respect trigger once', () => { getByText('true'); }); +test('should trigger onChange', () => { + const onChange = jest.fn(); + render(); + + mockAllIsIntersecting(true); + expect(onChange).toHaveBeenLastCalledWith( + true, + expect.objectContaining({ intersectionRatio: 1, isIntersecting: true }), + ); + + mockAllIsIntersecting(false); + expect(onChange).toHaveBeenLastCalledWith( + false, + expect.objectContaining({ intersectionRatio: 0, isIntersecting: false }), + ); +}); + test('should respect skip', () => { const { getByText, rerender } = render( , diff --git a/src/index.tsx b/src/index.tsx index 3db8f941..9f738883 100644 --- a/src/index.tsx +++ b/src/index.tsx @@ -35,6 +35,8 @@ export interface IntersectionOptions extends IntersectionObserverInit { trackVisibility?: boolean; /** IntersectionObserver v2 - Set a minimum delay between notifications */ delay?: number; + /** Call this function whenever the in view state changes */ + onChange?: (inView: boolean, entry: IntersectionObserverEntry) => void; } export interface IntersectionObserverProps extends IntersectionOptions { @@ -44,9 +46,6 @@ export interface IntersectionObserverProps extends IntersectionOptions { * assigned to the element root. */ children: (fields: RenderProps) => React.ReactNode; - - /** Call this function whenever the in view state changes */ - onChange?: (inView: boolean, entry: IntersectionObserverEntry) => void; } /** diff --git a/src/stories/Hooks.story.tsx b/src/stories/Hooks.story.tsx index 2a94cd24..07b109c4 100644 --- a/src/stories/Hooks.story.tsx +++ b/src/stories/Hooks.story.tsx @@ -92,7 +92,7 @@ const Template: Story = ({ style, className, lazy, ...rest }) => { const { options, error } = useValidateOptions(rest); const { ref, inView, entry } = useInView(!error ? options : {}); const [isLoading, setIsLoading] = useState(lazy); - action('Inview')(inView, entry); + action('InView')(inView, entry); useEffect(() => { if (isLoading) setIsLoading(false); diff --git a/src/useInView.tsx b/src/useInView.tsx index c0cdde25..c8dd8689 100644 --- a/src/useInView.tsx +++ b/src/useInView.tsx @@ -43,11 +43,16 @@ export function useInView({ skip, initialInView, fallbackInView, + onChange, }: IntersectionOptions = {}): InViewHookResponse { const unobserve = React.useRef(); + const callback = React.useRef(); const [state, setState] = React.useState({ inView: !!initialInView, }); + // Store the onChange callback in a `ref`, so we can access the latest instance inside the `useCallback`. + callback.current = onChange; + const setRef = React.useCallback( (node: Element | null) => { if (unobserve.current !== undefined) { @@ -63,6 +68,7 @@ export function useInView({ node, (inView, entry) => { setState({ inView, entry }); + if (callback.current) callback.current(inView, entry); if (entry.isIntersecting && triggerOnce && unobserve.current) { // If it should only trigger once, unobserve the element after it's inView