Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IntersectionObserver in useEffect with TypeScript and Next js

I'm trying to use IntersectionObserver in UseEffect and it works fine but TypeScript is complaining about cachedRef. It says: Argument of type 'HTMLDivElement | null' is not assignable to parameter of type 'Element'.

I've seen this question but can't figure out how to apply it to my code. If even possible.

const StickyNav = ({ children, stuckClasses, unstuckClasses }: Props) => {
  const [stuck, setStuck] = useState(false)
  const ref = useRef<HTMLDivElement | null>(null)
  const classes = stuck ? stuckClasses : unstuckClasses

  useEffect(() => {
    const cachedRef = ref.current
    const observer = new IntersectionObserver(
      ([e]) => setStuck(e.intersectionRatio < 1),
      { threshold: [1], rootMargin: "-91px 0px 91px 0px" }
    )

    // const cachedRef: HTMLDivElement | null
    // Argument of type 'HTMLDivElement | null' is not assignable to parameter of type 'Element'.
    // Type 'null' is not assignable to type 'Element'.ts(2345)
    observer.observe(cachedRef)
    return () => observer.unobserve(cachedRef)
  }, [ref])

  return (
    <div ref={ref}>
      <Container>
        {children}
      </Container>
    </div>
  )
}

Any ideas? Thanks!

like image 902
J C Avatar asked Feb 05 '26 12:02

J C


1 Answers

Just needed to check if ref.current exists in useEffect.

useEffect(() => {
  if (!ref.current) return
  ...
like image 94
J C Avatar answered Feb 08 '26 17:02

J C



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!