@utilityjs/use-is-in-viewport
v1.0.0
Published
A React hook that tells you when an element enters or leaves the viewport.
Downloads
2
Maintainers
Readme
A React hook that tells you when an element enters or leaves the viewport.
(Reuses observer instances where possible)
npm i @utilityjs/use-is-in-viewport | yarn add @utilityjs/use-is-in-viewport
Usage
const App: React.FC = () => {
const { registerNode, isInViewport } = useIsInViewport();
console.log(`is red box in the viewport? ${isInViewport}`);
return (
<div className="app">
<div style={{ height: 300,backgroundColor: "black" }}></div>
<div style={{ height: 300,backgroundColor: "black" }}></div>
<div style={{ height: 300,backgroundColor: "black" }}></div>
<div
ref={registerNode}
style={{
height: 300,
backgroundColor: "red"
}}
></div>
<div style={{ height: 300,backgroundColor: "black" }}></div>
<div style={{ height: 300,backgroundColor: "black" }}></div>
</div>
);
};
API
useIsInViewport( options?)
interface HookOptions {
once?: boolean;
disabled?: boolean;
}
interface HookConsumer {
registerNode: <T extends HTMLElement>(node: T | null) => void;
isInViewport: boolean;
}
declare const useIsInViewport: (
options?: (IntersectionObserverInit & HookOptions) | undefined
) => HookConsumer;
options.once
- (default: false
)
Only trigger the callback once. (unless you have toggled disabled
option.)
options.disabled
- (default: false
)
Skip creating the observer.
You can use this to enable and disable the observer as needed.
options.threshold
- (default: [0, 1]
)
Read the MDN Web Doc
options.root
- (default: null
)
Read the MDN Web Doc
options.rootMargin
- (default: 0px
)
Read the MDN Web Doc