Blog Posts

No results for undefinedPowered by Algolia

DailyLog

React Custom Hook useSticky

September 03, 2020

React useful custom hooks

useSticky

import { useState, useEffect } from "react"

const useSticky = fixRef => {
  const [isFix, setIsFix] = useState(false)

  useEffect(() => {
    const stickyPosY = fixRef.current.getBoundingClientRect().top

    const onScroll = () => {
      if (window.scrollY > stickyPosY) {
        setIsFix(true)
      } else {
        setIsFix(false)
      }
    }
    window.addEventListener("scroll", onScroll, true)

    return () => {
      window.removeEventListener("scroll", onScroll, true)
    }
  }, [])

  return {
    isFix,
  }
}
export default useSticky

getBoundingClientRect

The Element.getBoundingClientRect() method returns the size of an element and its position relative to the viewport.

The element’s size is equal to its width/height + padding + border-width in the case that the standard box model is being used, or width/height only if box-sizing: border-box has been set on it.

The returned value is a DOMRect object which is the union of the rectangles returned by getClientRects() for the element, i.e., the CSS border-boxes associated with the element. The result is the smallest rectangle which contains the entire element, with read-only left, top, right, bottom, x, y, width, and height properties describing the overall border-box in pixels. Properties other than width and height are relative to the top-left of the viewport.