### Install react-intersection-observer Source: https://context7.com/thebuilder/react-intersection-observer/llms.txt Install the library using npm. ```bash npm install react-intersection-observer --save ``` -------------------------------- ### Install react-intersection-observer Source: https://github.com/thebuilder/react-intersection-observer/blob/main/storybook/stories/Recipes.mdx Install the library using npm or yarn. ```bash npm install react-intersection-observer yarn add react-intersection-observer ``` -------------------------------- ### Start Storybook Development Server Source: https://github.com/thebuilder/react-intersection-observer/blob/main/CONTRIBUTING.md Start the Storybook development server to view and test components. This command is used for local development. ```shell pnpm dev ``` -------------------------------- ### Polyfill Installation and Usage Source: https://github.com/thebuilder/react-intersection-observer/blob/main/README.md Instructions on how to install and import the intersection-observer polyfill for broader browser compatibility. ```APIDOC ## Polyfill You can install the `intersection-observer` polyfill using yarn: ```sh yarn add intersection-observer ``` Then, import it directly into your application: ```js import "intersection-observer"; ``` For Webpack users, dynamic imports can be used to load the polyfill only when needed: ```js async function loadPolyfills() { if (typeof window.IntersectionObserver === "undefined") { await import("intersection-observer"); } } ``` ``` -------------------------------- ### Install Dependencies with PNPM Source: https://github.com/thebuilder/react-intersection-observer/blob/main/CONTRIBUTING.md Install project dependencies using PNPM. This command should be run after cloning the repository. ```shell pnpm install ``` -------------------------------- ### Install intersection-observer Polyfill Source: https://github.com/thebuilder/react-intersection-observer/blob/main/README.md Install the intersection-observer polyfill using Yarn. This package provides the IntersectionObserver API for browsers that do not natively support it. ```sh yarn add intersection-observer ``` -------------------------------- ### Setup Vitest Intersection Mocking Source: https://github.com/thebuilder/react-intersection-observer/blob/main/README.md Use this setup in your Vitest tests if the environment does not support global beforeEach/afterEach or Jest/Vitest mocking functions. It ensures IntersectionObserver is mocked correctly. ```javascript import { vi, beforeEach, afterEach } from "vitest"; import { setupIntersectionMocking, resetIntersectionMocking, } from "react-intersection-observer/test-utils"; beforeEach(() => { setupIntersectionMocking(vi.fn); }); afterEach(() => { resetIntersectionMocking(); }); ``` -------------------------------- ### Using `IntersectionObserver` directly Source: https://github.com/thebuilder/react-intersection-observer/blob/main/storybook/stories/Recipes.mdx For advanced use cases or when not using React components, you can directly use the native `IntersectionObserver` API. This example shows how to set it up and observe an element. ```javascript const observer = new IntersectionObserver((entries, observer) => { entries.forEach(entry => { if (entry.isIntersecting) { console.log('Element is visible:', entry.target); // Optionally unobserve after it's visible // observer.unobserve(entry.target); } }); }, { rootMargin: '0px', threshold: 0.1 }); const elementToObserve = document.querySelector('#myElement'); if (elementToObserve) { observer.observe(elementToObserve); } ``` -------------------------------- ### Run Tests with Vitest Source: https://github.com/thebuilder/react-intersection-observer/blob/main/CONTRIBUTING.md Execute all project tests using the Vitest test runner. Ensure all tests pass before submitting changes. ```shell pnpm test ``` -------------------------------- ### useInView Hook and InView Component Options Source: https://github.com/thebuilder/react-intersection-observer/blob/main/README.md These options can be provided as the `options` argument to the `useInView` hook or as props to the `` component. ```APIDOC ## Options for useInView and InView Component ### Description These options configure the behavior of the Intersection Observer API used by the `useInView` hook and the `` component. ### Parameters #### Options Object - **root** (Element) - Optional - The parent element to use as the viewport for observing intersections. Defaults to the browser's document viewport. - **rootMargin** (string) - Optional - Margin around the root element. Similar to CSS margin, e.g., "10px 20px 30px 40px". Can also use percentages. - **threshold** (number or number[]) - Optional - A number between 0 and 1, or an array of numbers, indicating the percentage of the target element that must be visible to trigger the observer. - **onChange** ((inView, entry) => void) - Optional - Callback function executed when the intersection status changes. Receives `inView` (boolean) and the `IntersectionObserverEntry`. - **trackVisibility** (boolean) - Optional - If true, the observer will track visibility changes. Defaults to `false`. - **delay** (number) - Optional - Minimum delay in milliseconds between notifications when `trackVisibility` is true. Must be at least 100 if `trackVisibility` is true. - **skip** (boolean) - Optional - If true, the IntersectionObserver will not be created. Defaults to `false`. - **triggerOnce** (boolean) - Optional - If true, the observer will only trigger once. Defaults to `false`. - **initialInView** (boolean) - Optional - Sets the initial `inView` state. Defaults to `false`. - **fallbackInView** (boolean) - Optional - The value to use for `inView` if the IntersectionObserver API is not available. Defaults to `undefined`. ### Notes - The `useOnInView` hook accepts the same options as `useInView` except for `onChange`, `initialInView`, and `fallbackInView`. ``` -------------------------------- ### Implement Lazy Image Loading with useInView Source: https://context7.com/thebuilder/react-intersection-observer/llms.txt Use the `useInView` hook to conditionally render images only when they enter the viewport. Configure `triggerOnce` to load the image only once and `rootMargin` to pre-load images before they become fully visible, preventing layout shifts with aspect ratio containers. ```jsx import React from "react"; import { useInView } from "react-intersection-observer"; const LazyImage = ({ src, alt, width, height }) => { const { ref, inView } = useInView({ triggerOnce: true, // Only load once rootMargin: "200px 0px", // Start loading 200px before visible }); const aspectRatio = (height / width) * 100; return (
{inView && ( {alt} )}
); }; // Usage const Gallery = () => (
); ``` -------------------------------- ### Use useInView hook with object destructuring Source: https://github.com/thebuilder/react-intersection-observer/blob/main/README.md Demonstrates using the `useInView` hook with object destructuring to obtain the ref, inView status, and entry object. ```js const { ref, inView, entry } = useInView(options); ``` -------------------------------- ### Import Markdown from Storybook Source: https://github.com/thebuilder/react-intersection-observer/blob/main/storybook/stories/Intro.mdx Import the Markdown component from Storybook's addon-docs/blocks to render Markdown content. ```javascript import { Markdown } from '@storybook/addon-docs/blocks'; import Readme from '../readme.md?raw'; {Readme} ``` -------------------------------- ### Import intersection-observer Polyfill Source: https://github.com/thebuilder/react-intersection-observer/blob/main/README.md Import the intersection-observer polyfill directly into your application. This ensures the IntersectionObserver API is available. ```js import "intersection-observer"; ``` -------------------------------- ### Storybook Markdown Rendering Source: https://github.com/thebuilder/react-intersection-observer/blob/main/storybook/stories/Recipes.mdx This snippet demonstrates how to render Markdown content within Storybook using the `@storybook/addon-docs/blocks` and `?raw` import for loading the Markdown file. ```jsx import { Markdown } from '@storybook/addon-docs/blocks'; import Recipes from '../../docs/Recipes.md?raw'; {Recipes} ``` -------------------------------- ### InView Component and Hook Options Source: https://github.com/thebuilder/react-intersection-observer/blob/main/storybook/readme.md These options can be provided as props to the `` component or as the options argument when using the hooks. ```APIDOC ## InView Component and Hook Options ### Description These options configure the behavior of the Intersection Observer used by the `react-intersection-observer` library. They can be passed as props to the `` component or as the `options` argument to the `useInView` and `useInView` hooks. ### Method N/A (Configuration options) ### Endpoint N/A (Configuration options) ### Parameters #### Props/Options - **root** (Element | null) - Optional - The element that is used as a viewport for checking the visibility of a target. Defaults to the browser viewport if not specified or null. - **rootMargin** (string) - Optional - Margin around the root. Values are similar to CSS `margin`, e.g., "10px 20px 30px 40px" (top, right, bottom, left). Defaults to '0px'. - **threshold** (number | number[]) - Optional - A number or an array of numbers between 0 and 1 indicating the percentage of the target that should be visible before triggering the observer. Defaults to 0. - **trackVisibility** (boolean) - Optional - If true, the observer will track the visibility of the target element. Defaults to false. Requires a minimum delay of 100ms if set to true. - **delay** (number) - Optional - The minimum delay in milliseconds between notifications for a given target. Must be at least 100 if `trackVisibility` is true. Defaults to undefined. - **skip** (boolean) - Optional - If true, the IntersectionObserver will not be created. This can be used to conditionally enable/disable the observer. Defaults to false. - **triggerOnce** (boolean) - Optional - If true, the observer will only trigger once. Defaults to false. - **initialInView** (boolean) - Optional - Sets the initial state of the `inView` boolean. Useful for scenarios where an element is expected to be in view initially. Defaults to false. - **fallbackInView** (boolean) - Optional - Specifies a fallback value for `inView` if the IntersectionObserver API is not available in the client. Defaults to undefined. If not set, an error will be thrown in unsupported environments. ### Request Example ```jsx {({ inView, ref }) => (
{inView ? 'Element is in view' : 'Element is not in view'}
)}
``` ### Response #### Success Response (200) - **inView** (boolean) - Indicates whether the observed element is currently within the viewport according to the specified options. - **ref** (RefObject) - A React ref object to attach to the element you want to observe. #### Response Example ```json { "inView": true, "ref": { "current": "
" } } ``` ``` -------------------------------- ### Use useInView hook with array destructuring Source: https://github.com/thebuilder/react-intersection-observer/blob/main/README.md Demonstrates using the `useInView` hook with array destructuring, allowing customization of returned field names. ```js const [ref, inView, entry] = useInView(options); ``` -------------------------------- ### Using with Multiple Elements Source: https://github.com/thebuilder/react-intersection-observer/blob/main/storybook/stories/Recipes.mdx Observe multiple elements by mapping over data and assigning a unique ref to each element. The `inView` status will correspond to each element individually. ```jsx import React from 'react'; import { useInView } from 'react-intersection-observer'; const data = [ { id: 1, text: 'Item 1' }, { id: 2, text: 'Item 2' }, { id: 3, text: 'Item 3' }, ]; function MyListComponent() { return (
{data.map(item => ( ))}
); } function Item({ text }) { const { ref, inView } = useInView({ triggerOnce: true, }); return (

{text}

{inView ? 'Visible' : 'Not Visible'}

); } ``` -------------------------------- ### Track Element Impressions with Callback Source: https://github.com/thebuilder/react-intersection-observer/blob/main/docs/Recipes.md Track when an element enters the viewport by using the useOnInView hook. This is useful for firing analytics events. Configure triggerOnce and rootMargin for precise tracking. ```jsx import * as React from "react"; import { useOnInView } from "react-intersection-observer"; const TrackImpression = () => { const ref = useOnInView((inView) => { if (inView) { // Fire a tracking event to your tracking service of choice. dataLayer.push("Section shown"); // Here's a GTM dataLayer push } }, { triggerOnce: true, rootMargin: "-100px 0", }); return (
Exemplars sunt zeluss de bassus fuga. Credere velox ducunt ad audax amor.
); }; export default TrackImpression; ``` -------------------------------- ### useOnInView Hook for Callbacks Source: https://context7.com/thebuilder/react-intersection-observer/llms.txt Utilize the `useOnInView` hook for performance-critical scenarios like analytics. It returns a ref callback and does not trigger re-renders. Configure options like `threshold`, `triggerOnce`, and `rootMargin`. ```jsx import React from "react"; import { useOnInView } from "react-intersection-observer"; const TrackableSection = ({ sectionId }) => { const trackingRef = useOnInView( (inView, entry) => { if (inView) { // Element entered viewport - log impression console.log(`Section ${sectionId} visible`, entry.target); // Example: Send analytics event // analytics.track('section_viewed', { sectionId }); } else { // Element left viewport console.log(`Section ${sectionId} hidden`); } }, { threshold: 0.5, triggerOnce: true, rootMargin: "-100px 0px", } ); return (

This section is being tracked without re-renders

Perfect for analytics and impression tracking

); }; export default TrackableSection; ``` -------------------------------- ### Basic Usage of useInView Hook Source: https://github.com/thebuilder/react-intersection-observer/blob/main/storybook/stories/Recipes.mdx Use the useInView hook to track the visibility of an element. It returns a boolean `inView` and a `ref` to attach to the observed element. ```jsx import React from 'react'; import { useInView } from 'react-intersection-observer'; function MyComponent() { const { ref, inView } = useInView({ /* Optional options */ triggerOnce: true, }); return (

{inView ? 'Element is in view' : 'Element is not in view'}

); } ``` -------------------------------- ### Basic useInView hook implementation Source: https://github.com/thebuilder/react-intersection-observer/blob/main/README.md A basic implementation of the `useInView` hook in a React component. Assign the returned ref to the DOM element you want to monitor. ```jsx import React from "react"; import { useInView } from "react-intersection-observer"; const Component = () => { const { ref, inView, entry } = useInView({ /* Optional options */ threshold: 0, }); return (

{`Header inside viewport ${inView}.`}

); }; ``` -------------------------------- ### Using the `as` prop for custom elements Source: https://github.com/thebuilder/react-intersection-observer/blob/main/storybook/stories/Recipes.mdx Render the observed element as a different HTML tag by using the `as` prop. This is useful for semantic HTML or when working with other component libraries. ```jsx import React from 'react'; import { useInView } from 'react-intersection-observer'; function MyComponent() { const { ref, inView } = useInView({ triggerOnce: true, }); return (

{inView ? 'Visible Heading' : 'Hidden Heading'}

); } ``` -------------------------------- ### Dynamically Load intersection-observer Polyfill Source: https://github.com/thebuilder/react-intersection-observer/blob/main/README.md Conditionally import the intersection-observer polyfill using dynamic imports. This approach loads the polyfill only when the IntersectionObserver API is not natively supported, optimizing bundle size. ```js async function loadPolyfills() { if (typeof window.IntersectionObserver === "undefined") { await import("intersection-observer"); } } ``` -------------------------------- ### InView Component with Render Props Source: https://context7.com/thebuilder/react-intersection-observer/llms.txt Employ the `` component with a render prop pattern for fine-grained control over rendering based on visibility. It passes `ref`, `inView`, and `entry` to its children function. ```jsx import { InView } from "react-intersection-observer"; const AnimatedSection = () => ( {({ inView, ref, entry }) => (

Animated Content

This fades in when 25% visible

{entry && Ratio: {entry.intersectionRatio}}
)}
); export default AnimatedSection; ``` -------------------------------- ### Low-level API: observe function Source: https://github.com/thebuilder/react-intersection-observer/blob/main/README.md Details on using the `observe` function from the `react-intersection-observer` library for advanced control over IntersectionObserver instances. ```APIDOC ## Low level API: observe The `observe` method allows direct interaction with IntersectionObserver instances, useful for advanced use cases outside of React or when fine-grained control is required. ### Method ```js import { observe } from "react-intersection-observer"; const destroy = observe(element, callback, options); ``` ### Parameters #### Path Parameters This method does not use path parameters. #### Query Parameters This method does not use query parameters. #### Request Body This method does not use a request body. ### Parameters Table | Name | Type | Required | Description | |---|---|---|---| | **element** | `Element` | true | DOM element to observe | | **callback** | `ObserverInstanceCallback` | true | The callback function that Intersection Observer will call | | **options** | `IntersectionObserverInit` | false | The options for the Intersection Observer | ### Returns The `observe` method returns an `unobserve` function. This function must be called to destroy the observer and clean up resources. ```js // Example of calling the returned unobserve function const destroyObserver = observe(myElement, handleIntersection, { threshold: 0.5 }); // Later, to stop observing: destroyObserver(); ``` > [!IMPORTANT] > This low-level API is generally not needed for typical React usage but provides flexibility for specialized scenarios. ``` -------------------------------- ### Track Visibility with Intersection Observer v2 Source: https://github.com/thebuilder/react-intersection-observer/blob/main/README.md Use `trackVisibility` and `delay` options with `useInView` to monitor if an element is visible, especially for ad exposure tracking. Note browser support and potential TypeScript `lib.d.ts` extensions. ```jsx const TrackVisible = () => { const { ref, entry } = useInView({ trackVisibility: true, delay: 100 }); return
{entry?.isVisible}
; }; ``` -------------------------------- ### Jest Configuration for IntersectionObserver Mock Source: https://github.com/thebuilder/react-intersection-observer/blob/main/README.md Configure Jest or Vitest to use `react-intersection-observer/test-utils` for mocking IntersectionObserver in all tests. Add this to `setupFilesAfterEnv` for Jest or `setupFiles` for Vitest. ```javascript module.exports = { setupFilesAfterEnv: ["react-intersection-observer/test-utils"], }; ``` -------------------------------- ### Assign Multiple Refs with useCallback Source: https://context7.com/thebuilder/react-intersection-observer/llms.txt Combine multiple refs, including the one from `useInView`, onto a single element by using `useCallback` to ensure a stable function identity. This prevents unnecessary re-renders. ```jsx import React, { useRef, useCallback } from "react"; import { useInView } from "react-intersection-observer"; const ComponentWithMultipleRefs = () => { const myRef = useRef(null); const { ref: inViewRef, inView } = useInView(); // Combine refs with useCallback for stable identity const setRefs = useCallback( (node) => { // Assign to useRef's current property myRef.current = node; // Call the callback ref from useInView inViewRef(node); }, [inViewRef] ); return (

In view: {inView.toString()}

Direct ref access: {myRef.current?.tagName}

); }; ``` -------------------------------- ### Lazy Image Load with IntersectionObserver Source: https://github.com/thebuilder/react-intersection-observer/blob/main/docs/Recipes.md Implement lazy image loading by only setting the image src when the element enters the viewport. Use rootMargin for pre-loading and triggerOnce to avoid repeated checks. ```jsx import React from "react"; import { useInView } from "react-intersection-observer"; const LazyImage = ({ width, height, src, ...rest }) => { const { ref, inView } = useInView({ triggerOnce: true, rootMargin: "200px 0px", }); return (
{inView ? ( ) : null}
); }; export default LazyImage; ``` -------------------------------- ### Use InView Hook Source: https://github.com/thebuilder/react-intersection-observer/blob/main/storybook/readme.md Use the useInView hook to monitor the inView state of a component. Assign the returned ref to the DOM element you want to track. Optional configuration options can be passed. ```jsx import React from 'react'; import { useInView } from 'react-intersection-observer'; const Component = () => { const { ref, inView, entry } = useInView({ /* Optional options */ threshold: 0, }); return (

{`Header inside viewport ${inView}.`}

); }; ``` -------------------------------- ### InView Component with Render Props Source: https://github.com/thebuilder/react-intersection-observer/blob/main/storybook/readme.md Use the InView component with a render prop function to access inView state and a ref. The ref should be attached to the DOM element to be monitored. The IntersectionObserverEntry is also available. ```jsx import { InView } from 'react-intersection-observer'; const Component = () => ( {({ inView, ref, entry }) => (

{`Header inside viewport ${inView}.`}

)}
); export default Component; ``` -------------------------------- ### IntersectionObserver v2 Visibility Tracking Source: https://context7.com/thebuilder/react-intersection-observer/llms.txt Enable IntersectionObserver v2 API extension with `trackVisibility: true` to track actual element visibility, detecting occlusion by other elements or filters. A `delay` of at least 100ms is required. ```jsx import { useInView } from "react-intersection-observer"; const VisibilityTracker = () => { const { ref, entry } = useInView({ trackVisibility: true, // Enable v2 visibility tracking delay: 100, // Required: minimum 100ms delay between notifications }); return (

Element is actually visible: {entry?.isVisible ? "Yes" : "No"}

This detects occlusion by other elements

); }; ``` -------------------------------- ### Configure Default Fallback for IntersectionObserver Support Source: https://context7.com/thebuilder/react-intersection-observer/llms.txt Set the global fallback behavior using defaultFallbackInView when IntersectionObserver is not supported. By default, an error is thrown. This allows graceful handling of unsupported environments. ```jsx import { defaultFallbackInView, useInView } from "react-intersection-observer"; // Set global fallback - all hooks will use this value when IO is unsupported defaultFallbackInView(true); // Elements are always considered "in view" // OR defaultFallbackInView(false); // Elements are always considered "out of view" // Per-hook override const Component = () => { const { ref, inView } = useInView({ fallbackInView: true, // Override global setting for this hook }); return
{inView ? "Visible" : "Hidden"}
; }; ``` -------------------------------- ### Mock All IntersectionObservers as Intersecting Source: https://github.com/thebuilder/react-intersection-observer/blob/main/README.md Use `mockAllIsIntersecting` to simulate all IntersectionObservers being in view. This is useful for testing components that rely on IntersectionObserver without needing to manually trigger intersections. ```javascript import React from "react"; import { screen, render } from "@testing-library/react"; import { useInView } from "react-intersection-observer"; import { mockAllIsIntersecting, mockIsIntersecting, intersectionMockInstance, } from "react-intersection-observer/test-utils"; const HookComponent = ({ options }) => { const { ref, inView } = useInView(options); return (
{inView.toString()}
); }; test("should create a hook inView", () => { render(); // This causes all (existing) IntersectionObservers to be set as intersecting mockAllIsIntersecting(true); screen.getByText("true"); }); test("should create a hook inView with threshold", () => { render(); mockAllIsIntersecting(0.1); screen.getByText("false"); // Once the threshold has been passed, it will trigger inView. mockAllIsIntersecting(0.3); screen.getByText("true"); }); test("should mock intersecing on specific hook", () => { render(); const wrapper = screen.getByTestId("wrapper"); // Set the intersection state on the wrapper. mockIsIntersecting(wrapper, 0.5); screen.getByText("true"); }); test("should create a hook and call observe", () => { const { getByTestId } = render(); const wrapper = getByTestId("wrapper"); // Access the `IntersectionObserver` instance for the wrapper Element. const instance = intersectionMockInstance(wrapper); expect(instance.observe).toHaveBeenCalledWith(wrapper); }); ``` -------------------------------- ### InView Component with Plain Children Source: https://github.com/thebuilder/react-intersection-observer/blob/main/storybook/readme.md Render the InView component with plain children. The component will create a wrapping DOM element. Use the onChange handler to monitor state changes. Additional props are passed to the HTML element. ```jsx import { InView } from 'react-intersection-observer'; const Component = () => ( console.log('Inview:', inView)}>

Plain children are always rendered. Use onChange to monitor state.

); export default Component; ``` -------------------------------- ### Customizing Intersection Observer Options Source: https://github.com/thebuilder/react-intersection-observer/blob/main/storybook/stories/Recipes.mdx Configure the Intersection Observer with options like `root`, `rootMargin`, and `threshold` for fine-grained control over when the observer triggers. ```jsx import React from 'react'; import { useInView } from 'react-intersection-observer'; function MyComponent() { const { ref, inView } = useInView({ root: document.querySelector('#scrollArea'), // element that is the viewport rootMargin: '0px', threshold: 0.5 }); return (

{inView ? 'Partially visible' : 'Not visible'}

); } ``` -------------------------------- ### Use On In View Hook Source: https://github.com/thebuilder/react-intersection-observer/blob/main/README.md Use the `useOnInView` hook for performance-critical scenarios where re-renders should be avoided. It directly accesses the DOM element and triggers a callback with intersection state and entry details. ```javascript const inViewRef = useOnInView( (inView, entry) => { if (inView) { // Do something with the element that came into view console.log("Element is in view", entry.target); } else { console.log("Element left view", entry.target); } }, options // Optional IntersectionObserver options ); ``` ```jsx import React from "react"; import { useOnInView } from "react-intersection-observer"; const Component = () => { // Track when element appears without causing re-renders const trackingRef = useOnInView( (inView, entry) => { if (inView) { // Element is in view - perhaps log an impression console.log("Element appeared in view", entry.target); } else { console.log("Element left view", entry.target); } }, { /* Optional options */ threshold: 0.5, triggerOnce: true, }, ); return (

This element is being tracked without re-renders

); }; ``` -------------------------------- ### InView Component Props Source: https://github.com/thebuilder/react-intersection-observer/blob/main/storybook/readme.md The InView component accepts several props to customize its behavior and rendering. ```APIDOC ## InView Component Props ### Description This section details the available props for the `` component. ### Props #### `as` - **Type**: `string` - **Default**: `'div'` - **Required**: false - **Description**: Render the wrapping element as this element. Defaults to `div`. #### `children` - **Type**: `({ref, inView, entry}) => React.ReactNode` or `ReactNode` - **Default**: N/A - **Required**: true - **Description**: 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` - **Type**: `(inView, entry) => void` - **Default**: N/A - **Required**: false - **Description**: Call this function whenever the in view state changes. It will receive the `inView` boolean, alongside the current `IntersectionObserverEntry`. ``` -------------------------------- ### InView Component with Render Props Source: https://github.com/thebuilder/react-intersection-observer/blob/main/README.md Use the `` component with render props to access `inView` state, a `ref` for the monitored DOM element, and the `IntersectionObserverEntry` details. The initial `false` notification is suppressed. ```jsx import { InView } from "react-intersection-observer"; const Component = () => ( {({ inView, ref, entry }) => (

{`Header inside viewport ${inView}.`}

)}
); export default Component; ``` -------------------------------- ### useInView Hook for Reactive State Source: https://context7.com/thebuilder/react-intersection-observer/llms.txt Use the `useInView` hook to monitor element visibility and trigger re-renders. It returns a ref callback, `inView` boolean, and `IntersectionObserverEntry`. Supports object and array destructuring. ```jsx import React from "react"; import { useInView } from "react-intersection-observer"; const Component = () => { // Object destructuring (recommended) const { ref, inView, entry } = useInView({ threshold: 0, rootMargin: "0px", triggerOnce: false, skip: false, initialInView: false, fallbackInView: true, onChange: (inView, entry) => { console.log("Visibility changed:", inView); }, }); // Alternative: Array destructuring // const [ref, inView, entry] = useInView({ threshold: 0.5 }); return (

{`Header is ${inView ? "visible" : "hidden"}`}

{entry && (

Intersection ratio: {entry.intersectionRatio.toFixed(2)}

)}
); }; export default Component; ``` -------------------------------- ### Observe Low-Level API for Direct DOM Observation Source: https://context7.com/thebuilder/react-intersection-observer/llms.txt Use the observe function for direct IntersectionObserver management outside React's lifecycle. It provides full control over observer creation and destruction. Remember to call the returned unobserve function for cleanup. ```jsx import { observe } from "react-intersection-observer"; // Direct DOM element observation const element = document.getElementById("my-element"); const unobserve = observe( element, (inView, entry) => { console.log("Element in view:", inView); console.log("Intersection ratio:", entry.intersectionRatio); console.log("Target element:", entry.target); if (inView) { // Perform action when visible element.classList.add("visible"); } }, { root: null, // Use viewport as root rootMargin: "0px", threshold: [0, 0.25, 0.5, 0.75, 1], // Multiple trigger points } ); // Later: cleanup when done unobserve(); ``` -------------------------------- ### Mock IntersectionObserver in Tests Source: https://context7.com/thebuilder/react-intersection-observer/llms.txt Utilize test utilities from `react-intersection-observer/test-utils` to mock IntersectionObserver behavior in Jest and Vitest. This allows precise control over element visibility states for testing components that rely on `useInView`. ```jsx import { render, screen } from "@testing-library/react"; import { useInView } from "react-intersection-observer"; import { mockAllIsIntersecting, mockIsIntersecting, intersectionMockInstance, setupIntersectionMocking, resetIntersectionMocking, } from "react-intersection-observer/test-utils"; // Component under test const TestComponent = ({ threshold = 0 }) => { const { ref, inView } = useInView({ threshold }); return (
{inView ? "Visible" : "Hidden"}
); }; // For non-Jest/Vitest environments, manual setup required: // beforeEach(() => setupIntersectionMocking(vi.fn)); // afterEach(() => resetIntersectionMocking()); describe("IntersectionObserver tests", () => { test("triggers inView when intersecting", () => { render(); // Initially not in view expect(screen.getByText("Hidden")).toBeInTheDocument(); // Mock all observers as intersecting mockAllIsIntersecting(true); expect(screen.getByText("Visible")).toBeInTheDocument(); }); test("respects threshold values", () => { render(); // 30% visible - below threshold mockAllIsIntersecting(0.3); expect(screen.getByText("Hidden")).toBeInTheDocument(); // 50% visible - meets threshold mockAllIsIntersecting(0.5); expect(screen.getByText("Visible")).toBeInTheDocument(); }); test("mocks specific element intersection", () => { render(); const wrapper = screen.getByTestId("wrapper"); // Mock intersection for specific element mockIsIntersecting(wrapper, true); expect(screen.getByText("Visible")).toBeInTheDocument(); }); test("accesses observer instance for spying", () => { render(); const wrapper = screen.getByTestId("wrapper"); const observerInstance = intersectionMockInstance(wrapper); expect(observerInstance.observe).toHaveBeenCalledWith(wrapper); }); }); ``` -------------------------------- ### Trigger Animations on Viewport Entry Source: https://github.com/thebuilder/react-intersection-observer/blob/main/docs/Recipes.md Use IntersectionObserver to trigger CSS animations when an element becomes visible in the viewport. Configure triggerOnce for a single animation and use rootMargin or threshold to control the trigger point. ```jsx import React from "react"; import { useInView } from "react-intersection-observer"; const LazyAnimation = () => { const { ref, inView } = useInView({ triggerOnce: true, rootMargin: "-100px 0px", }); return (
👋
); }; export default LazyAnimation; ``` -------------------------------- ### Set Local Fallback InView Option Source: https://github.com/thebuilder/react-intersection-observer/blob/main/README.md Override the global fallback value by setting `fallbackInView` directly on the `useInView` hook or `` component. This allows for specific fallback behavior per component. ```jsx import React from "react"; import { useInView } from "react-intersection-observer"; const Component = () => { const { ref, inView, entry } = useInView({ fallbackInView: true, }); return (

{`Header inside viewport ${inView}.`}

); }; ``` -------------------------------- ### Set Default Fallback InView Source: https://github.com/thebuilder/react-intersection-observer/blob/main/README.md Configure the default fallback behavior for IntersectionObserver. Set to `true` or `false` to ensure consistent behavior across tests when IntersectionObserver is not supported. ```javascript import { defaultFallbackInView } from "react-intersection-observer"; defaultFallbackInView(true); // or `false` - whichever consistent behavior makes the most sense for your use case. ``` -------------------------------- ### Set Global Fallback InView Value Source: https://github.com/thebuilder/react-intersection-observer/blob/main/README.md Globally configure the `inView` value to use when `IntersectionObserver` is not supported. This ensures graceful failure of the application. ```javascript import { defaultFallbackInView } from "react-intersection-observer"; defaultFallbackInView(true); // or 'false' ``` -------------------------------- ### Low-level observe API Usage Source: https://github.com/thebuilder/react-intersection-observer/blob/main/README.md Utilize the low-level `observe` function from `react-intersection-observer` for advanced control over IntersectionObserver instances. Remember to call the returned `unobserve` function to clean up the observer. ```js import { observe } from "react-intersection-observer"; const destroy = observe(element, callback, options); ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.