useImpressionRef
useImpressionRef は、特定の DOM 要素が画面に表示されている時間を計測し、要素がビューポートに入ったときや出たときにコールバックを実行する React フックです。 IntersectionObserver と Visibility API を使って、要素の表示状態を追跡します。
インターフェース
ts
function useImpressionRef<Element extends HTMLElement>(
options: UseImpressionRefOptions
): (element: Element | null) => void;パラメータ
- optionsrequired · UseImpressionRefOptions
要素の表示状態を追跡するためのオプション。
- options.onImpressionStart() => void
要素が表示領域に入ったときに実行するコールバック関数。
- options.onImpressionEnd() => void
要素が表示領域から出たときに実行するコールバック関数。
- options.timeThresholdnumber · 0
要素が表示されている必要がある最小時間(ミリ秒単位)。
- options.areaThresholdnumber · 0
表示されている必要がある要素の最小割合(0 から 1)。
- options.rootMarginstring
検出領域を調整するためのマージン。
- options.onImpressionStart() => void
戻り値
- (element: Element | null) => void
対象の要素を設定する関数です。この関数を
ref属性に設定すると、要素の表示状態が変わるたびにコールバックを実行します。
使用例
tsx
import { useImpressionRef } from 'react-simplikit';
function Component() {
const ref = useImpressionRef<HTMLDivElement>({
onImpressionStart: () => console.log('Element entered view'),
onImpressionEnd: () => console.log('Element exited view'),
timeThreshold: 1000,
areaThreshold: 0.5,
});
return <div ref={ref}>Track my visibility!</div>;
}