The 'src' properties in nextjs/image are of different types and therefore cannot be used interchangeably

I'm currently using React Dropzone to upload multiple images in my basic application. To display the types of images that are being dropped, I created a separate component with TypeScript. However, Next.js is throwing an error when it comes to the image source:

'{ src: string; alt: string; }' is not compatible with type 'IntrinsicAttributes & ImageProps'.
  Type '{ src: string; alt: string; }' does not align with type 'ObjectImageProps'.
    The types for the 'src' property are conflicting.
      String type cannot be assigned to StaticImport type.

RenderFiles.ts:

import { IFile } from "../../libs/types";
import { sizeInMb } from "../../libs/sizeInMb";
import { FunctionComponent } from "react";
import Image from "next/image"

const RenderFile: FunctionComponent<{
  file: IFile;
}> = ({ file: { formate, sizeInBytes, name } }) => {
  return (
    <div>
      <Image src={`/images/${formate}.png`} alt="image"/>
      <span>{name}</span>
      <span>{sizeInMb(sizeInBytes)}</span>
    </div>
  );
};

export default RenderFile;

types.ts:

export interface IFile {
  name: string;
  sizeInBytes: number;
  formate: string | number;
  id?: string;
}

Where did I go wrong with the src prop?

Answer №1

The problem lies in the fact that next/image's component Image requires a rather complex type called ImageProps as its props:

type StringImageProps = {
  src: string
} & (
  | { width?: never; height?: never; layout: 'fill' }
  | {
      width: number | string
      height: number | string
      layout?: Exclude<LayoutValue, 'fill'>
    }
) &
  (
    | {
        placeholder?: Exclude<PlaceholderValue, 'blur'>
        blurDataURL?: never
      }
    | { placeholder: 'blur'; blurDataURL: string }
  )

type ObjectImageProps = {
  src: StaticImport
  width?: number | string
  height?: number | string
  layout?: LayoutValue
  placeholder?: PlaceholderValue
  blurDataURL?: never
}

export type ImageProps = Omit<
  JSX.IntrinsicElements['img'],
  'src' | 'srcSet' | 'ref' | 'width' | 'height' | 'loading' | 'style'
> & {
  loader?: ImageLoader
  quality?: number | string
  priority?: boolean
  loading?: LoadingValue
  unoptimized?: boolean
  objectFit?: ImgElementStyle['objectFit']
  objectPosition?: ImgElementStyle['objectPosition']
} & (StringImageProps | ObjectImageProps)

If you're not importing images locally, then you must adhere to the structure defined by StringImageProps. To fulfill this requirement, you need to provide one of the following prop sets:

<Image src={string} layout="fill" />
// or
<Image src={string} width={number} height={number} /> // with an optional `layout` prop that is not set to 'fill'

Both options may include an optional placeholder (not set to 'blur') or a mandatory placeholder: 'blur' and blurDataURL: string.

After conforming to these requirements, you can then provide the native HTML attributes such as alt for the image.

Answer №2

Found the solution by importing the type ImageLoaderProps.

Here's an example:

import Image from 'next/image';
import type { ImageLoaderProps } from 'next/image';

const customLoader = ({ src, width, quality }: ImageLoaderProps) => {
  return `https://example.com/?${src}?w=${width}&q=${quality}`;
};

export default function DisplayComponent(props: Record<string, string>) {
  const { imageURL } = props;
  return (
        <Image
          loader={customLoader}
          src={`/${imageURL}`}
          width="20%"
          height="20%"
        />
  );
}

Answer №4

To convert a string to any data type, simply cast it as any.

<Image src={'string' as any} alt='Pic' />

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Enhance your Next.js application's Chart.js graph by incorporating react-icons for pointStyles

Issue: I am attempting to utilize the MdNavigation icon from react-icons as a pointStyle in Chart.js within a Next.js application. Despite my efforts, I seem to be encountering difficulties that could stem from how I have configured the file-loader in ne ...

Having trouble making generics work with extends in Typescript

I am facing an issue when trying to limit input to an object, but unfortunately, it is not working correctly: displayModal<T extends {[key: string]: any}, U>(component: Type<AbstractDialogComponent<T, U>>, options?: ModalDialogOption ...

Exploring tailored markup features in Next.js version 13

I am trying to optimize my website for social media sharing on platforms like WhatsApp. I have been experimenting with different methods to set custom markup in Next.js 13, but haven't achieved the desired outcome yet. Your help and insight are greatl ...

Validating patterns in Angular without using a form

Seeking guidance on validating user input in Angular6 PrimeNG pInputText for a specific URL pattern, such as , possibly triggered on blur event. This particular field used to be part of a form but has since been relocated to a more complex 6-part form int ...

Interacting between components using Angular 2 services

I am attempting to implement bidirectional service communication using Angular. I have followed the instructions provided in the documentation here: https://angular.io/docs/ts/latest/cookbook/component-communication.html#!#bidirectional-service interactio ...

Sendgrid NodeJS has already received the previous email that was sent

My current tech stack includes NextJS, Firebase (Auth, DB, etc...), Vercel for hosting, OVH Domains, and using Node with NextJS for the backend. Recently, I have been experiencing strange behavior when sending emails using Sendgrid library or API v3 direc ...

Are union types strictly enforced?

Is it expected for this to not work as intended? class Animal { } class Person { } type MyUnion = Number | Person; var list: Array<MyUnion> = [ "aaa", 2, new Animal() ]; // Is this supposed to fail? var x: MyUnion = "jjj"; // Should this actually ...

Sharing JSON Web Tokens (JWT) between client and server in NextJs

My NextJs application has an HTTP service that handles API calls to an external backend server, serving as an API endpoint (NodeJs app separate from NextJs). The issue at hand is: I need to authenticate and receive a JWT token. I also need to store this ...

I encountered an error stating "Buffer is not defined" originating from the Deode/Encode Stream Bundle.js script, not from my own code

I've encountered a major issue while attempting to update my npm project to webpack 5, and now I'm left with just one persistent error: bundle.js:1088566 Uncaught ReferenceError: Buffer is not defined at bundle.js:1044980:24 ...

Typescript type for selecting only string[] keys in an object

I am looking for a specific type: interface Filter<P extends object> { label: string; options: FilterOption[]; key: StringArrayKeyOf<P>; } The definition of StringArrayKeyOf is as follows: type StringArrayKeyOf<T extends object> = ...

Tips for mock nesting a repository in TypeORM?

I'm struggling to figure out how to stub a nested Repository in TypeORM. Can anyone assist me in creating a sinon stub for the code snippet below? I attempted to use some code from another Stack Overflow post in my test file, but it's not working ...

Once I deployed my Nextjs website on Vercel, I encountered an issue when attempting to log in with Google as it kept redirecting me to localhost:

I rely on supabase for my backend operations. While attempting to log in using Google, I need to ensure that it does not redirect me to localhost. ...

Leveraging the power of Next.js and a tailored deployment strategy using Express and Node

Recently, I encountered an issue while trying to deploy my app that utilizes Next.js on the frontend (including some getStaticProps function) and a custom express/node.js backend on Azure. The backend is connected to MySQL, although I don't believe th ...

Connection to mongo is currently unavailable for Middleware next

This code snippet shows a middleware for Next, which is designed to read the subdomain and check if it exists in the database. import { getValidSubdomain } from '@/lib/getValidSubdomain'; import { NextResponse } from 'next/server' impor ...

How to configure mat-sort-header in Angular Material for mat-table

My current table is created using Angular Material: <mat-table *ngIf="!waiting" class="table-general table-summary" #table [dataSource]="dataSource" matSort> <mat-header-row class="header_row" *matHeaderRowDef="headerKeys"></mat-header ...

The <Link> component in Next.js redirects to a 404 error page

I recently developed a next.js application and encountered an issue when attempting to link to another page. Whenever I try linking, I receive a 404 error. I have read that this is a known bug, but I am unsure of how to resolve it. Upon creating the app, I ...

Tips for retrieving and presenting information from a JSON document in a React TypeScript application

I am struggling to display data in a list format using TypeScript. I am able to fetch the data but unable to display it properly. I am currently using map to iterate through an array of JSON objects. //json file [ { "id": "6s", ...

What's preventing me from using just one comparison condition in TypeScript?

The issue at hand is quite simple: An error occurred because I tried to compare a number with a 'Ref<number>' object. It seems ridiculous that I can't compare two numbers, but as I am new to Typescript, I would greatly appreciate some ...

Guide on displaying information on a pie chart in Angular 2 using ng2-charts

How can I display data on a pie chart like this? Like shown in the image below: <canvas baseChart class="pie" [data]="Data" [labels]="Labels" [colors]="Colors" [chartType]="pieChartType"> </canvas> public Labels:string[]=['F ...

What are the steps to enable screen sharing within an Electron application?

I am currently working on developing two applications for screen sharing within a LAN setting using Electron, React, and TypeScript. The first app will capture the screen stream and broadcast it via UDP, while the second app, running on multiple devices, w ...