A tiny React hook and component to detect viewport visibility
npm install react-viewport-visibility
once, threshold, and rootMargin
bash
npm install react-viewport-visibility
`
or with Yarn:
`bash
yarn add react-viewport-visibility
`
🚀 Usage
$3
`tsx
import React, { useRef } from 'react';
import { useVisibility } from 'react-viewport-visibility';
function MyComponent() {
const ref = useRef(null);
const { isVisible } = useVisibility(ref, { threshold: 0.5 });
return (
{isVisible ? 'Visible' : 'Not Visible'}
);
}
`
$3
`tsx
import React, { useState } from 'react';
import { VisibilitySensor } from 'react-viewport-visibility';
function App() {
const [visible, setVisible] = useState(false);
return (
{visible ? 'I am visible!' : 'Scroll to reveal me'}
);
}
`
📚 API
$3
- ref: A React ref pointing to a DOM element
- options: { threshold?: number, once?: boolean, rootMargin?: string }
Returns:
`ts
{
isVisible: boolean,
ratio: number
}
`
$3
| Prop | Type | Description |
|---------------------|---------------------------------------|----------------------------------------|
| threshold | number | Visibility ratio (default: 0.1) |
| once | boolean | Stop observing after first visibility |
| rootMargin | string | Margin around root (default: "0px") |
| onVisibilityChange| (visible: boolean) => void | Callback when visibility changes |
| children | React.ReactNode | Children to render |
🛠 Development
`bash
npm install
npm run build
``