J C
J C

Reputation: 85

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!

Upvotes: 3

Views: 7195

Answers (1)

J C
J C

Reputation: 85

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

useEffect(() => {
  if (!ref.current) return
  ...

Upvotes: 4

Related Questions