Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting a ref on the NextJS Image component creates a typescript error

I'm trying to refactor one of my components to use typescript. As you see below, I'm using a reference on the NextJS Image component and trying to set the type

import { useRef } from 'react'
import Image, { ImageProps } from 'next/image'


type BannerBlockProps = {
  image?: ImageProps[]
}

const BannerBlock = (props: BannerBlockProps) => {
  const imageRef = useRef<HTMLImageElement >(null)

  return (
  
        <div className='BannerBlock-imageWrapper' >
          <Image className="BannerBlock-image" src={image[0].src} alt={image[0].alt} width={image[0].width} height={image[0].height} ref={imageRef}/>
        </div>
  )
}

export default BannerBlock

I then get the following typescript error on the Image ref property: :

(property) ref: RefObject Type '{ className: string; src: string | StaticImport; alt: string | undefined; width: string | number | undefined; height: string | number | undefined; ref: RefObject; }' is not assignable to type 'IntrinsicAttributes & Omit<DetailedHTMLProps<ImgHTMLAttributes, HTMLImageElement>, "src" | ... 4 more ... | "loading"> & { ...; }'. Property 'ref' does not exist on type 'IntrinsicAttributes & Omit<DetailedHTMLProps<ImgHTMLAttributes, HTMLImageElement>, "src" | ... 4 more ... | "loading"> & {

It happens because in next/dist/client/image.d.ts the ref type is omitted on the ImageProps:

export declare type ImageProps = Omit<JSX.IntrinsicElements['img'], 'src' | 'srcSet' | 'ref' | 'width' | 'height' | 'loading'> & {
    src: string | StaticImport;
    width?: number | string;
    height?: number | string;
    layout?: LayoutValue;
    loader?: ImageLoader;
    quality?: number | string;
    priority?: boolean;
    loading?: LoadingValue;
    lazyRoot?: React.RefObject<HTMLElement> | null;
    lazyBoundary?: string;
    placeholder?: PlaceholderValue;
    blurDataURL?: string;
    unoptimized?: boolean;
    objectFit?: ImgElementStyle['objectFit'];
    objectPosition?: ImgElementStyle['objectPosition'];
    onLoadingComplete?: OnLoadingComplete;
};

The error disappears when I remove | 'ref' from the list of omitted properties. Why is this property omitted? Is it bad practice to use the ref property on an Image component? It's easily fixed putting a wrapper div on the image component and add the reference there, but I am curious to why this is not possible and if I'm doing this right.

like image 865
Lennart de Knikker Avatar asked Oct 19 '25 10:10

Lennart de Knikker


1 Answers

Passing ref to next/image seems to be added in next 13.0.6.

like image 191
Anton Kouliavtsev Avatar answered Oct 20 '25 23:10

Anton Kouliavtsev



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!