useRef Тип "null" не может быть назначен для типа "HTMLElement"

'use client'
import { ProductWithRelations } from '@/app/@types/prisma'
import { useCategoryStore } from '@/store/category'
import { useEffect, useRef } from 'react'
import { useIntersection } from 'react-use'
import { ProductCard, Title } from '..'

type Props = {
    title: string
    items: ProductWithRelations[]
    className?: string
    categoryId: number
    listClassName?: string
}
const ProductsGroupList = ({ title, items, className, categoryId }: Props) => {
    const setActiveCategoryId = useCategoryStore(state => state.setActiveId)
    const intersectionRef = useRef(null)
    const intersection = useIntersection(intersectionRef, {
        threshold: 0.8,
    })
    useEffect(() => {
        if (intersection?.isIntersecting) {
            setActiveCategoryId(categoryId)
        }
    }, [categoryId, intersection?.isIntersecting, setActiveCategoryId])
    return (
        <div className={className} id={title} ref={intersectionRef}>
            <Title text={title} size='lg' className=' mb-5 font-extrabold' />
            <div className='grid grid-cols-3 gap-[50px]'>
                {items.map(product => (
                    <ProductCard
                        key={product.id}
                        id={product.id}
                        name={product.name}
                        imageUrl={product.imageUrl}
                        price={product.items[0].price}
                        ingredients={product.ingredients}
                    />
                ))}
            </div>
        </div>
    )
}

export { ProductsGroupList }

Type error: Argument of type 'RefObject<null>' is not assignable to parameter of type 'RefObject<HTMLElement>'.
  Type 'null' is not assignable to type 'HTMLElement'.

Next.js build worker exited with code: 1 and signal: null

введите сюда описание изображения

Подскажите как испавить


Ответы (2 шт):

Автор решения: ksa

Подскажите как испавить

Пример прямо из документации по use-intersection

import React, { useRef } from 'react';
import { useIntersection } from 'use-intersection';
 
const Component: React.FC = () => {
  const target = useRef<HTMLDivElement>(null);
  const intersecting = useIntersection(target);
 
  return <div ref={target}>{intersecting ? 'visible' : 'invisible'}</div>;
};

https://www.npmjs.com/package/use-intersection

в данном случае useIntersection взят из react-use, а не из use-intersection

Посмотрел документацию по react-use... Так там так же описывается

useIntersection(
  ref: RefObject<HTMLElement>,
  options: IntersectionObserverInit,
): IntersectionObserverEntry | null;

https://github.com/streamich/react-use/blob/master/docs/useIntersection.md

→ Ссылка
Автор решения: stormX

это должно помочь

const intersectionRef = useRef<HTMLDivElement>(null)
const intersection = useIntersection(
    intersectionRef as React.RefObject<HTMLElement>
→ Ссылка