diff options
| author | Armand Philippot <git@armandphilippot.com> | 2023-10-31 17:41:43 +0100 |
|---|---|---|
| committer | Armand Philippot <git@armandphilippot.com> | 2023-11-11 18:15:27 +0100 |
| commit | 2844a2bd71dcf1eb17a53992c10129b7496332e0 (patch) | |
| tree | 6b59044ade226c7dad7d1e64c9586e8d6ff0374b /src/utils/hooks/use-scrollbar-width/use-scrollbar-width.ts | |
| parent | 3ff4c37a7a2c40340c17f9e6c1754444bce0f839 (diff) | |
feat(components): add an Overlay component
* add useScrollbarWidth hook
* add useScrollLock hook
* add a new component to lock scroll with an overlay (it can be useful
especially on small screens to prevent background contents to be
scrolled)
Diffstat (limited to 'src/utils/hooks/use-scrollbar-width/use-scrollbar-width.ts')
| -rw-r--r-- | src/utils/hooks/use-scrollbar-width/use-scrollbar-width.ts | 42 |
1 files changed, 42 insertions, 0 deletions
diff --git a/src/utils/hooks/use-scrollbar-width/use-scrollbar-width.ts b/src/utils/hooks/use-scrollbar-width/use-scrollbar-width.ts new file mode 100644 index 0000000..19bfebc --- /dev/null +++ b/src/utils/hooks/use-scrollbar-width/use-scrollbar-width.ts @@ -0,0 +1,42 @@ +import { useCallback, useEffect, useState } from 'react'; + +/** + * Retrieve the scrollbar width of the window. + * + * @returns {number} The scrollbar width. + */ +export const getScrollbarWidth = (): number => { + const defaultWidth = 15; + + if (typeof window === 'undefined') return defaultWidth; + + return window.document.body.clientWidth + ? window.innerWidth - window.document.body.clientWidth + : 0; +}; + +/** + * React hook to retrieve the current scrollbar width of the window. + * + * @returns {number} The scrollbar width. + */ +export const useScrollBarWidth = (): number => { + const [scrollbarWidth, setScrollbarWidth] = useState(0); + + const updateScrollbarWidth = useCallback(() => { + setScrollbarWidth(getScrollbarWidth()); + }, []); + + useEffect(() => { + updateScrollbarWidth(); + window.addEventListener('resize', updateScrollbarWidth); + window.addEventListener('orientationchange', updateScrollbarWidth); + + return () => { + window.removeEventListener('resize', updateScrollbarWidth); + window.removeEventListener('orientationchange', updateScrollbarWidth); + }; + }, [updateScrollbarWidth]); + + return scrollbarWidth; +}; |
