Reputation: 85
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
Reputation: 85
Just needed to check if ref.current exists in useEffect.
useEffect(() => {
if (!ref.current) return
...
Upvotes: 4