diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 7d6ba3a9..c7576e64 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -1,7 +1,7 @@ -# Contribution Guidelines +# Contribution guidelines -Welcome to `react-intersection-observer`! I'm thrilled that you're interested in -contributing. Here are some guidelines to help you get started. +Thanks for wanting to contribute to `react-intersection-observer`. Here's what +you need to know to get started. The codebase is written in TypeScript and uses PNPM workspaces: @@ -12,22 +12,22 @@ The codebase is written in TypeScript and uses PNPM workspaces: ## Development -Start by forking the repository, and after cloning it locally you can install -the dependencies using [PNPM](https://pnpm.io/): +Fork the repository, clone it locally, and install the dependencies with +[PNPM](https://pnpm.io/): ```shell pnpm install ``` -Then you can start the development surfaces with the `dev` task: +Then start both apps with the `dev` task: ```shell pnpm dev ``` -Use `pnpm dev:storybook` or `pnpm dev:docs` to start one surface at a time. +Use `pnpm dev:storybook` or `pnpm dev:docs` to start one at a time. -## Semantic Versioning +## Semantic versioning `react-intersection-observer` follows Semantic Versioning 2.0 as defined at http://semver.org. This means that releases will be numbered with the following @@ -39,52 +39,47 @@ format: - Backwards-compatible enhancements will increment the minor version. - Bug fixes and documentation changes will increment the patch version. -## Pull Request Process +## Pull requests -Fork the repository and create a branch for your feature/bug fix. +Create a branch on your fork for the fix or feature, then: -- Add tests for your feature/bug fix. -- Ensure that all tests pass before submitting your pull request. -- Update the README.md file if necessary. -- Ensure that your commits follow the conventions outlined in the next section. +- Add tests for the change. +- Make sure all tests pass. +- Update `README.md` if the change affects it. +- Follow the commit conventions below. -### Commit Message Conventions +### Commit message conventions -- We follow the - [Conventional Commits](https://www.conventionalcommits.org/en/v1.0.0/) - Conventions, so the generated release notes stay readable. This means that - your commit messages should have the following format: +Commits follow +[Conventional Commits](https://www.conventionalcommits.org/en/v1.0.0/), so the +generated release notes stay readable: `: ` -Here's what each part of the commit message means: +- `` is the kind of change. Use `feat` for new features, `fix` for bug + fixes, `docs` for documentation, and `chore` for everything that doesn't touch + the code itself, such as dependency updates. +- `` is a short description of the change. -- ``: The type of change that you're committing. Valid types include - `feat` for new features, `fix` for bug fixes, `docs` for documentation - changes, and `chore` for changes that don't affect the code itself (e.g. - updating dependencies). -- ``: A short description of the change. +### Code style and linting -### Code Style and Linting - -`react-intersection-observer` uses [Biome](https://biomejs.dev/) for code -formatting and linting. Please ensure that your changes are formatted with Biome before -submitting your pull request. +`react-intersection-observer` uses [Biome](https://biomejs.dev/) for formatting +and linting. Format your changes with Biome before opening a pull request. ### Testing `react-intersection-observer` uses [Vitest](https://vitest.dev/) for testing. -Please ensure that your changes are covered by tests, and that all tests pass -before submitting your pull request. +Cover your changes with tests, and make sure the whole suite passes before +opening a pull request. -You can run the package tests with the `test` task. Component tests run in -Vitest Browser Mode with Playwright; SSR tests run in a separate Node project. +Run the package tests with the `test` task. Component tests run in Vitest +Browser Mode with Playwright, and SSR tests run in a separate Node project. ```shell pnpm test ``` -Build every published and documentation surface with: +Build the package and both apps with: ```shell pnpm build:all @@ -107,6 +102,6 @@ The workflow bumps the version, commits and tags it, builds the package, publishes it to npm, and creates a GitHub release with generated notes. `main` is protected, so the version commit is pushed with a short-lived token -minted from a GitHub App that is listed as a bypass actor on the branch -ruleset. The app's id lives in the `RELEASE_APP_ID` variable and its private key -in the `RELEASE_APP_KEY` secret. +minted from a GitHub App listed as a bypass actor on the branch ruleset. The +app's id lives in the `RELEASE_APP_ID` variable, and its private key in the +`RELEASE_APP_KEY` secret. diff --git a/README.md b/README.md index a112e9b0..22e200f7 100644 --- a/README.md +++ b/README.md @@ -8,30 +8,30 @@ [![Downloads](http://img.shields.io/npm/dm/react-intersection-observer.svg)](http://npm-stat.com/charts.html?package=react-intersection-observer) ![npm package minimized gzipped size](https://img.shields.io/bundlejs/size/react-intersection-observer?exports=InView%2C%20useOnInView%2C%20useInView&externals=react&format=both) -A React implementation of the [Intersection Observer API](https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API) -to tell you when an element enters or leaves the viewport. Contains [Hooks](#useinview-hook), [render props](#render-props), and [plain children](#plain-children) implementations. +A React implementation of the [Intersection Observer API](https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API) +that tells you when an element enters or leaves the viewport. Use it for scroll +animations, lazy loading, impression tracking, and infinite scroll. It ships +[hooks](#useinview-hook), [render props](#render-props), and +[plain children](#plain-children). ## Features -- 🪝 **Hooks or Component API** - With `useInView` and `useOnInView` it's easier - than ever to monitor elements -- ⚡️ **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 -- 🧪 **Ready to test** - Mocks the Intersection Observer for easy testing with - [Jest](https://jestjs.io/) or [Vitest](https://vitest.dev/) -- 🌳 **Tree-shakeable** - Only include the parts you use -- 💥 **Tiny bundle** - Around **~1.15kB** for `useInView` and **~1.6kB** for - `` +- **Hooks or component API** - `useInView` for React state, `useOnInView` for + callbacks, `` for render props and wrapper elements. +- **Shared observers** - Observers with matching options are reused, so watching + many elements stays cheap. +- **Matches the native API** - Options map straight to + `IntersectionObserverInit`. +- **Written in TypeScript** - Types ship with the package. +- **Ready to test** - Mocks the Intersection Observer for + [Jest](https://jestjs.io/) and [Vitest](https://vitest.dev/). +- **Tree-shakeable** - Only the parts you import end up in your bundle. +- **Small** - Around 1.15kB gzipped for `useInView`, 1.6kB for ``. [![Open in StackBlitz](https://developer.stackblitz.com/img/open_in_stackblitz.svg)](https://stackblitz.com/github/thebuilder/react-intersection-observer) ## Installation -Install the package with your package manager of choice: - ```sh npm install react-intersection-observer --save ``` @@ -48,13 +48,11 @@ const { ref, inView, entry } = useInView(options); const [ref, inView, entry] = useInView(options); ``` -The `useInView` hook makes it easy to monitor the `inView` state of your -components. Call the `useInView` hook with the (optional) [options](#options) -you need. It will return an array containing a `ref`, the `inView` status and -the current +Call `useInView` with the (optional) [options](#options) you need. It returns a +`ref`, the `inView` status, and the current [`entry`](https://developer.mozilla.org/en-US/docs/Web/API/IntersectionObserverEntry). -Assign the `ref` to the DOM element you want to monitor, and the hook will -report the status. +Assign the `ref` to the DOM element you want to watch, and the hook reports the +status. ```jsx import React from "react"; @@ -92,23 +90,22 @@ const inViewRef = useOnInView( ); ``` -The `useOnInView` hook provides a more direct alternative to `useInView`. It -takes a callback function and returns a ref that you can assign to the DOM -element you want to monitor. Whenever the element enters or leaves the viewport, -your callback will be triggered with the latest in-view state. +`useOnInView` takes a callback and returns a ref to assign to the DOM element +you want to watch. Whenever the element enters or leaves the viewport, the +callback runs with the latest in-view state. + +Differences from `useInView`: -Key differences from `useInView`: -- **No re-renders** - This hook doesn't update any state, making it ideal for - performance-critical scenarios -- **Direct element access** - Your callback receives the actual - IntersectionObserverEntry with the `target` element -- **Boolean-first callback** - The callback receives the current `inView` - boolean as the first argument, matching the `onChange` signature from - `useInView` -- **Similar options** - Accepts all the same [options](#options) as `useInView` - except `onChange`, `initialInView`, and `fallbackInView` +- **No re-renders** - The hook holds no state, so a visibility change never + triggers a render. +- **Direct element access** - The callback receives the + `IntersectionObserverEntry`, including the `target` element. +- **Boolean-first callback** - The first argument is the current `inView` + boolean, matching the `onChange` signature from `useInView`. +- **Same options** - Accepts every [option](#options) `useInView` does, except + `onChange`, `initialInView`, and `fallbackInView`. -> **Note:** Just like `useInView`, the initial `false` notification is skipped. Your callback fires the first time the element becomes visible (and on every subsequent enter/leave transition). +> **Note:** Just like `useInView`, the initial `false` notification is skipped. Your callback fires the first time the element becomes visible, then on every enter and leave transition after that. ```jsx import React from "react"; @@ -119,7 +116,7 @@ const Component = () => { const trackingRef = useOnInView( (inView, entry) => { if (inView) { - // Element is in view - perhaps log an impression + // Element is in view, so log an impression console.log("Element appeared in view", entry.target); } else { console.log("Element left view", entry.target); @@ -142,23 +139,21 @@ const Component = () => { ### Render props -To use the `` component, you pass it a function. It will be called -whenever the state changes, with the new value of `inView`. In addition to the -`inView` prop, children also receive a `ref` that should be set on the -containing DOM element. This is the element that the Intersection Observer will -monitor. +Pass `` a function. It runs whenever the state changes, with the new +value of `inView`. Children also receive a `ref` that you set on the containing +DOM element. That element is the one the Intersection Observer watches. -If you need it, you can also access the +The [`IntersectionObserverEntry`](https://developer.mozilla.org/en-US/docs/Web/API/IntersectionObserverEntry) -on `entry`, giving you access to all the details about the current intersection +is available on `entry` when you need the details of the current intersection state. ```jsx import { InView } from "react-intersection-observer"; - const Component = () => ( - - {({ inView, ref, entry }) => ( +const Component = () => ( + + {({ inView, ref, entry }) => (

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

@@ -166,17 +161,17 @@ import { InView } from "react-intersection-observer";
); - export default Component; - ``` +export default Component; +``` -> **Note:** `` mirrors the hook behaviour—it suppresses the very first `false` notification so render props and `onChange` handlers only run after a genuine visibility change. +> **Note:** `` behaves like the hooks. It suppresses the first `false` notification, so render props and `onChange` handlers only run after a real visibility change. ### Plain children -You can pass any element to the ``, and it will handle creating the -wrapping DOM element. Add a handler to the `onChange` method, and control the -state in your own component. Any extra props you add to `` will be -passed to the HTML element, allowing you set the `className`, `style`, etc. +Pass any element to `` and it creates the wrapping DOM element for +you. Add a handler to `onChange` and keep the state in your own component. Extra +props on `` go to the HTML element, so you can set `className`, `style`, +and the rest. ```jsx import { InView } from "react-intersection-observer"; @@ -191,54 +186,52 @@ export default Component; ``` > [!NOTE] -> When rendering a plain child, make sure you keep your HTML output -> semantic. Change the `as` to match the context, and add a `className` to style -> the ``. The component does not support Ref Forwarding, so if you -> need a `ref` to the HTML element, use the Render Props version instead. +> When rendering a plain child, keep your HTML output semantic. Change `as` to +> match the context, and add a `className` to style the ``. The +> component does not forward refs, so use the render props version if you need a +> `ref` to the HTML element. ## API ### Options -Provide these as the options argument in the `useInView` hook or as props on the -**``** component. +Pass these as the options argument to `useInView`, or as props on ``. | Name | Type | Default | Description | | ---------------------- | ------------------------- | ----------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| **root** | `Element` | `document` | The Intersection Observer 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. | +| **root** | `Element` | `document` | The element whose bounds count as the viewport for the target. It must be an ancestor of the target. With `null`, the document viewport is used. | | **rootMargin** | `string` | `'0px'` | Margin around the root. Can have values similar to the CSS margin property, e.g. `"10px 20px 30px 40px"` (top, right, bottom, left). Also supports percentages, to check if an element intersects with the center of the viewport for example `"-50% 0% -50% 0%"`. | | **scrollMargin** | `string` | `'0px'` | Margin around nested scroll containers that clip the target. Can have values similar to the CSS margin property, e.g. `"10px 20px 30px 40px"` (top, right, bottom, left). Unlike `rootMargin`, this grows or shrinks every scroll container's clipping rectangle within the root, including the root itself if it is a scroll container. | | **threshold** | `number` or `number[]` | `0` | 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` | Call this function whenever the in view state changes. It will receive the `inView` boolean, alongside the current `IntersectionObserverEntry`. | -| **trackVisibility** 🧪 | `boolean` | `false` | A boolean indicating whether this Intersection Observer will track visibility changes on the target. | -| **delay** 🧪 | `number` | `undefined` | 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` | 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. | +| **onChange** | `(inView, entry) => void` | `undefined` | Runs whenever the in view state changes, with the `inView` boolean and the current `IntersectionObserverEntry`. | +| **trackVisibility** | `boolean` | `false` | Experimental. Track visibility changes on the target, beyond plain intersection. See [Intersection Observer v2](#intersection-observer-v2). | +| **delay** | `number` | `undefined` | Experimental. Minimum delay in milliseconds between notifications for a given target. Must be at least `100` if `trackVisibility` is `true`. | +| **skip** | `boolean` | `false` | Skip creating the IntersectionObserver, so you can turn observation on and off. Setting `skip` while `inView` keeps the current state. | | **triggerOnce** | `boolean` | `false` | Only trigger the observer once. | -| **initialInView** | `boolean` | `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` | 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()` | +| **initialInView** | `boolean` | `false` | The starting value of `inView`. Set it to `true` when the element starts in the viewport and you want to trigger something when it leaves. | +| **fallbackInView** | `boolean` | `undefined` | The `inView` value to use when the client has no `IntersectionObserver`, instead of the default behavior of throwing. `defaultFallbackInView()` sets this globally. | `useOnInView` accepts the same options as `useInView` except `onChange`, `initialInView`, and `fallbackInView`. -### InView Props +### InView props The **``** component also accepts the following props: | Name | Type | Default | Description | | ------------ | ---------------------------------------------------- | ----------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | -| **as** | `IntrinsicElement` | `'div'` | Render the wrapping element as this element. Defaults to `div`. If you want to use a custom component, please use the `useInView` hook or a render prop instead to manage the reference explictly. | -| **children** | `({ref, inView, entry}) => ReactNode` or `ReactNode` | `undefined` | 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. | +| **as** | `IntrinsicElement` | `'div'` | Render the wrapping element as this element. Defaults to `div`. If you want to use a custom component, use the `useInView` hook or a render prop instead to manage the reference explicitly. | +| **children** | `({ref, inView, entry}) => ReactNode` or `ReactNode` | `undefined` | A function receiving `inView`, a `ref` to assign to the element root, and the `IntersectionObserverEntry` as `entry`. Pass a plain child instead to let `` create the wrapping element. | -### Intersection Observer v2 🧪 +### Intersection Observer v2 -The new -[v2 implementation of IntersectionObserver](https://developers.google.com/web/updates/2019/02/intersectionobserver-v2) -extends the original API, so you can track if the element is covered by another -element or has filters applied to it. Useful for blocking clickjacking attempts -or tracking ad exposure. +[Intersection Observer v2](https://developers.google.com/web/updates/2019/02/intersectionobserver-v2) +extends the original API, so you can track whether the element is covered by +another element or has filters applied to it. Useful for blocking clickjacking +attempts or tracking ad exposure. -To use it, you'll need to add the new `trackVisibility` and `delay` options. -When you get the `entry` back, you can then monitor if `isVisible` is `true`. +Add the `trackVisibility` and `delay` options, then check whether `isVisible` +is `true` on the `entry` you get back. ```jsx const TrackVisible = () => { @@ -247,18 +240,16 @@ const TrackVisible = () => { }; ``` -This is still a very new addition, so check -[caniuse](https://caniuse.com/#feat=intersectionobserver-v2) for current browser -support. If `trackVisibility` has been set, and the current browser doesn't -support it, a fallback has been added to always report `isVisible` as `true`. +Check [caniuse](https://caniuse.com/#feat=intersectionobserver-v2) for current +browser support. If you set `trackVisibility` and the browser doesn't support +it, the fallback always reports `isVisible` as `true`. -It's not added to the TypeScript `lib.d.ts` file yet, so you will also have to -extend the `IntersectionObserverEntry` with the `isVisible` boolean. +`isVisible` isn't in the TypeScript `lib.d.ts` file yet, so you also have to +extend `IntersectionObserverEntry` with the boolean yourself. ## Recipes -The `IntersectionObserver` itself is just a simple but powerful tool. Here's a -few ideas for how you can use it. +A few things you can build with it: - [Lazy image load](apps/docs/docs/guides/recipes.mdx#lazy-image-loading) - [Trigger animations](apps/docs/docs/guides/recipes.mdx#scroll-triggered-animation) @@ -282,9 +273,9 @@ function Component(props) { // Use `useCallback` so we don't recreate the function on each render const setRefs = useCallback( (node) => { - // Ref's from useRef needs to have the node assigned to `current` + // Refs from `useRef` need the node assigned to `current` ref.current = node; - // Callback refs, like the one from `useInView`, is a function that takes the node as an argument + // Callback refs, like the one from `useInView`, are functions that take the node inViewRef(node); }, [inViewRef], @@ -296,15 +287,13 @@ function Component(props) { ### `rootMargin` isn't working as expected -When using `rootMargin`, the margin gets added to the current `root` - If your -application is running inside a `