skip to Main Content
import React from "react";
import { useInView } from "react-intersection-observer";

type PhotoProps = {
    name: string;
    imgUrl: string;
};

export default function Photo({ name, imgUrl }: PhotoProps) {
    const { ref, inView } = useInView({
        threshold: 0.5,
    });

    return (
        <div ref={ref} className="photo--card">
            {inView ? <img src={imgUrl} alt={name} /> : <div className="Skeleton"></div>}
            <h4>{name}</h4>
        </div>
    );
}
the error is Type (node?: (Element | null)) => void is not assignable to type LegacyRef<HTMLDivElement> | undefined

i tried to specify ref as HTMLDivElement, but ref stops working then, also you need to destructure these components separatly in order to do that. Im new to typescript, so im definetely doing smth wrong, but neither google, nor chatGPT couldn`t solve this problen

2

Answers


  1. Try to cast the ref variable to MutableRefObject<HTMLDivElement>.

    Hope it could help.

    import React, { MutableRefObject } from "react";
    import { useInView } from "react-intersection-observer";
    
    type PhotoProps = {
        name: string;
        imgUrl: string;
    };
    
    export default function Photo({ name, imgUrl }: PhotoProps) {
        const { ref, inView } = useInView({
            threshold: 0.5,
        });
    
        return (
            <div ref={ref as React.MutableRefObject<HTMLDivElement>} className="photo--card">
                {inView ? <img src={imgUrl} alt={name} /> : <div className="Skeleton"></div>}
                <h4>{name}</h4>
            </div>
        );
    }
    
    Login or Signup to reply.
  2. In most cases with useInView from react-intersection-observer, using React.RefObject is sufficient because you typically don’t need to modify the ref object itself, only to use it to interact with the DOM element it refers to.

    <div ref={ref as React.RefObject<HTMLDivElement>} className="photo--card">
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search