useScrollHide
The useScrollHide
hook allows you to hide the scrollbars of a specified HTML element or the body of the document. This can be useful for modals or overlays where you want to prevent background scrolling.
Add the utility
npx @ivnatsr/ezreact add use-scroll-hide
import { useRef, useLayoutEffect } from 'react'
export function useScrollHide() { const elementRef = useRef(null) const defaultStyle = useRef({ overflow: 'auto' })
useLayoutEffect(() => { const getElement = () => elementRef.current ?? document.querySelector('body')
const hideScroll = () => { const element = getElement() defaultStyle.current.overflow = element.style.overflow element.style.overflow = 'hidden' }
const showScroll = () => { const element = getElement() element.style.overflow = defaultStyle.current.overflow }
hideScroll()
return showScroll }, [])
return elementRef}
import { useRef, useLayoutEffect, type CSSProperties } from 'react'
export function useScrollHide<ElementType extends HTMLElement>() { const elementRef = useRef<ElementType>(null) const defaultStyle = useRef<Required<Pick<CSSProperties, 'overflow'>>>({ overflow: 'auto' })
useLayoutEffect(() => { const getElement = () => elementRef.current ?? (document.querySelector('body') as HTMLElement)
const hideScroll = () => { const element = getElement() defaultStyle.current.overflow = element.style.overflow element.style.overflow = 'hidden' }
const showScroll = () => { const element = getElement() element.style.overflow = defaultStyle.current.overflow }
hideScroll()
return showScroll }, [])
return elementRef}
Return
This hook returns a ref that should be attached to the element whose scroll behavior you want to control. If you don’t attach this ref to any DOM element, it will default to body
.
Example
import { useScrollHide } from './path/to/use-scroll-hide'
const ScrollHideExample = () => { const elementRef = useScrollHide()
return ( <div ref={elementRef}> <h1>Content with hidden scrollbars</h1> <p>Scrollbars are hidden for this element.</p> </div> )}
export default ScrollHideExample