Initial commit
This commit is contained in:
@@ -0,0 +1,48 @@
|
||||
# useScrollPosition
|
||||
|
||||
Tracks the vertical scroll position of the window or a specific scrollable element.
|
||||
|
||||
## Signature
|
||||
|
||||
```ts
|
||||
function useScrollPosition(options?: { targetRef?: RefObject<HTMLElement | Document> }): number;
|
||||
```
|
||||
|
||||
### Options
|
||||
|
||||
| Option | Type | Default | Description |
|
||||
| ----------- | ------------------------------------ | ---------- | ------------------------------------------------------- |
|
||||
| `targetRef` | `RefObject<HTMLElement \| Document>` | `document` | Ref to a scrollable element; falls back to the document |
|
||||
|
||||
Returns the current `scrollY` (window) or `scrollTop` (element) as a number.
|
||||
|
||||
## Usage
|
||||
|
||||
```tsx
|
||||
// Track window scroll
|
||||
function ScrollProgress() {
|
||||
const scrollY = useScrollPosition();
|
||||
|
||||
return <div>Scrolled: {scrollY}px</div>;
|
||||
}
|
||||
```
|
||||
|
||||
```tsx
|
||||
// Track a specific scrollable container
|
||||
function VirtualList() {
|
||||
const containerRef = useRef<HTMLDivElement>(null);
|
||||
const scrollTop = useScrollPosition({ targetRef: containerRef });
|
||||
|
||||
return (
|
||||
<div ref={containerRef} style={{ overflowY: 'auto', height: 400 }}>
|
||||
{/* items */}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
## Notes
|
||||
|
||||
- Initial position is read synchronously on mount so there is no flash to `0`.
|
||||
- Automatically switches between `window.scrollY` and `element.scrollTop` based on the target.
|
||||
- Client-only (`'use client'`).
|
||||
Reference in New Issue
Block a user