Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

#185 create useIntersectionObserver hook #224

Merged
merged 8 commits into from
Oct 13, 2023
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
58 changes: 58 additions & 0 deletions src/hooks/useIntersectionObserver/useIntersectionObserver.mdx
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
import { Meta } from '@storybook/blocks';

<Meta title="hooks/useIntersectionObserver" />

# useIntersectionObserver

The Intersection Observer API provides a way to asynchronously observe changes in the intersection
of a target element with an ancestor element or with a top-level document's viewport.

The hook is a wrapper around the Intersection Observer API, so for full details and reference check
the [docs](https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API).

## Reference

```ts
export function useIntersectionObserver(
targetOrTargets: Unreffable<Element | null> | Array<Unreffable<Element | null>>,
callback: IntersectionObserverCallback,
options?: IntersectionObserverInit,
): void;
```

### Parameters

- `targetOrTargets` The element or array of elements to observe. Also accepts refs to elements.

- `callback: (entries: IntersectionObserverEntry[], observer: IntersectionObserver): void;` The
callback that gets executed when an intersection change is observed.
- `options: { root?: Element | Document | null; rootMargin?: string; threshold?: number | number[]; }`
Lets you control the circumstances under which the observer's callback is invoked. See the
[reference](https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API#creating_an_intersection_observer)
for details.

### Returns

`void`

## Usage

```tsx
function Component() {
const ref = useRef<HTMLDivElement>(null);

useIntersectionObserver(ref, (entries) => {
entries.forEach((entry) => {
// entry.boundingClientRect
// entry.intersectionRatio
// entry.intersectionRect
// entry.isIntersecting
// entry.rootBounds
// entry.target
// entry.time
});
});

return <div ref={ref}></div>;
}
```
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
/* eslint-disable react/jsx-no-bind, react/no-multi-comp, react/jsx-no-literals */
import type { StoryObj } from '@storybook/react';
import type { ReactElement } from 'react';
import { useRef, useState } from 'react';
import { useIntersectionObserver } from './useIntersectionObserver.js';

export default {
title: 'hooks/useIntersectionObserver',
};

function DemoComponent(): ReactElement {
const [isRedVisible, setIsRedVisible] = useState(false);
const containerRef = useRef<HTMLDivElement>(null);
const targetRef = useRef<HTMLDivElement>(null);
useIntersectionObserver(targetRef, ([entry]) => {
setIsRedVisible(entry.isIntersecting);
});

return (
<>
<p>
Scroll down in green element, red is currently{' '}
<strong>{!isRedVisible && 'NOT '}VISIBLE</strong>
</p>
<div ref={containerRef} style={{ height: 100, overflow: 'scroll', backgroundColor: 'green' }}>
<div ref={targetRef} style={{ height: 100, marginTop: 200, backgroundColor: 'red' }}></div>
</div>
</>
);
}

export const Demo: StoryObj = {
render() {
return <DemoComponent />;
},
};
37 changes: 37 additions & 0 deletions src/hooks/useIntersectionObserver/useIntersectionObserver.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import { useEffect } from 'react';
import { unref, type Unreffable } from '../../utils/unref/unref.js';

/**
* This hook creates an IntersectionObserver and uses it to observe
* the target element.
*
* For a full explanation of the IntersectionObserver API, check the docs:
* https://developer.mozilla.org/en-US/docs/Web/API/IntersectionObserver/IntersectionObserver
*
* @param targetOrTargets - The target or targets to observe
* @param callback - The callback to fire when the element resizes
* @param options - Optional options object
*/

export function useIntersectionObserver(
targetOrTargets: Unreffable<Element | null> | Array<Unreffable<Element | null>>,
callback: IntersectionObserverCallback,
options?: IntersectionObserverInit,
): void {
useEffect(() => {
const elements = (Array.isArray(targetOrTargets) ? targetOrTargets : [targetOrTargets]).map(
(target) => unref(target),
);

const intersectionObserverInstance = new IntersectionObserver(callback, options);
leroykorterink marked this conversation as resolved.
Show resolved Hide resolved
for (const element of elements) {
if (element) {
intersectionObserverInstance.observe(element);
}
}

return () => {
intersectionObserverInstance.disconnect();
};
}, [callback, options, targetOrTargets]);
leroykorterink marked this conversation as resolved.
Show resolved Hide resolved
}
1 change: 1 addition & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
/* PLOP_ADD_EXPORT */
export * from './hooks/useIntersectionObserver/useIntersectionObserver.js';
export * from './components/AutoFill/AutoFill.js';
export * from './hocs/ensuredForwardRef/ensuredForwardRef.js';
export * from './hooks/useBeforeMount/useBeforeMount.js';
Expand Down