-
Notifications
You must be signed in to change notification settings - Fork 1
/
useViewport.ts
61 lines (46 loc) · 1.77 KB
/
useViewport.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
51
52
53
54
55
56
57
58
59
60
61
import * as React from 'react';
const { useEffect, useState } = React
const getViewportWidth = (): number => {
const docClientWidth = document.documentElement
? document.documentElement.clientWidth
: 0;
const documentBodyWidth = document.body ? document.body.clientWidth : 0;
return window.innerWidth || docClientWidth || documentBodyWidth;
};
const getViewportHeight = (): number => {
const documentElement = document.documentElement;
const documentHeight = documentElement.clientHeight;
return window.innerHeight || documentHeight;
};
const getDocumentHeight = (): number => {
const documentElement = document.documentElement;
const documentHeight: number = documentElement.scrollHeight;
return documentHeight;
};
const useViewport = () => {
const [viewportWidth, setViewportWidth] = useState<number>(getViewportWidth());
const [viewportHeight, setViewportHeight] = useState<number>(getViewportHeight());
const [documentHeight, setDocumentHeight] = useState<number>(getDocumentHeight());
useEffect(() => {
window.addEventListener('resize', getWindowDimensions);
window.addEventListener('scroll', getScrollPosition);
return () => {
window.removeEventListener('resize', getWindowDimensions);
window.removeEventListener('scroll', getScrollPosition);
}
}, []);
const getWindowDimensions = (): void => {
setViewportWidth(getViewportWidth());
setViewportHeight(getViewportHeight());
setDocumentHeight(getDocumentHeight());
};
const getScrollPosition = (): void => {
setDocumentHeight(getDocumentHeight());
};
return {
documentHeight,
viewportHeight,
viewportWidth,
};
};
export { useViewport };