-
-
Notifications
You must be signed in to change notification settings - Fork 3.2k
/
Copy pathuseScroll.ts
50 lines (41 loc) · 1004 Bytes
/
useScroll.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
import { RefObject, useEffect } from 'react';
import useRafState from './useRafState';
import { off, on } from './misc/util';
export interface State {
x: number;
y: number;
}
const useScroll = (ref: RefObject<HTMLElement>): State => {
if (process.env.NODE_ENV === 'development') {
if (typeof ref !== 'object' || typeof ref.current === 'undefined') {
console.error('`useScroll` expects a single ref argument.');
}
}
const [state, setState] = useRafState<State>({
x: 0,
y: 0,
});
useEffect(() => {
const handler = () => {
if (ref.current) {
setState({
x: ref.current.scrollLeft,
y: ref.current.scrollTop,
});
}
};
if (ref.current) {
on(ref.current, 'scroll', handler, {
capture: false,
passive: true,
});
}
return () => {
if (ref.current) {
off(ref.current, 'scroll', handler);
}
};
}, [ref]);
return state;
};
export default useScroll;