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

I am in the process of creating a Nextjs website and I would like to integrate a Wordpress Blogs page. How can I achieve this integration?

After completing my website on Nextjs, I am now looking to integrate a Blogs page using Wordpress. Can anyone guide me on how to install Wordpress specifically for my Blogs Page and customize it accordingly? Your assistance with installing Wordpress on m ...

Understanding the significance of emitDecoratorMetadata in transpiled code

I have a question regarding the significance of the emitDecoratorMetadata option when transpiling TypeScript to JavaScript in an Angular 2 environment. If this option is set to false, and metadata is not included in the final code, what impact will it ha ...

Neglecting the inclusion of a property when verifying for empty properties

In the code snippet below, I have implemented a method to check for empty properties and return true if any property is empty. However, I am looking for a way to exclude certain properties from this check. Specifically, I do not want to include generalReal ...

Webpack is having trouble locating images within Nextjs

When I import static images with no issues using npm run dev, everything runs smoothly. However, when attempting to utilize npm run build or next build, it fails and prevents deployment to Vercel. next info Operating System: Platform: win32 ...

Other options besides React SSR

I've been tasked with adding server side rendering to a large project I inherited. The project uses a custom routing system based on a "builder JSON" taken by a main component to dynamically render components based on the route, catering to different ...

Unexpected errors are encountered when using ng serve

When I run the ng serve command, unexpected errors are occurring on my system. The errors include: PS C:\Users\SAYED-SADAT\Desktop\data\coding\itsm-frontend\itsm-frontend> ng serveYour global Angular CLI version (13.0 ...

Encountering an issue with MUI 5 where it is unable to access properties of undefined when utilizing makestyles

I recently finished building a react app using MUI-5 and everything was running smoothly. However, I've encountered a strange issue where my app refuses to start and I'm bombarded with multiple MUI errors. These errors started popping up after I ...

Tips for adding an extensive collection of fixed attributes to a function using Typescript

I am attempting to write a function that includes a lengthy list of static strings attached as properties, all returning the property as a string value: const arr = ["a", "b", "c"]; // there are around 140 items in the actual list const f = (tag: strin ...

Discovering the breakpoints for Angular ng-bootstrapUncover the angular ng

Utilizing ng-bootstrap in my latest project has allowed me to easily create a grid with breakpoints, like so: <div class="row"> <div class="col-sm-12 col-md-6 col-xl-4"></div> </div> Although these breakpoints are convenient, ...

Enhance the performance of your React/NextJS app by controlling the rendering of a component and focusing on updating

I'm facing an issue with my NextJS application that showcases a list of audio tracks using an <AudioTrackEntry> component. This component receives props like the Track Title and a Link to the audio file from an external data source. Within the ...

The automation script for Playwright/Puppeteer is having trouble properly handling `async...await` in a `for..loop` on the `/signup` page

Currently, I am faced with the challenge of automating rate-limit requests using a playwright automation script. The issue arises when the script keeps attempting to sign up with the email <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data ...

How can I extend a third-party JavaScript library in TypeScript using a declaration file?

Currently, I am working on creating a .d.ts file for an external library called nodejs-driver. While I have been able to map functions and objects successfully, I am struggling with incorporating the "inherit from objects defined in the JS library" conce ...

Display the 404 page from the reverse proxy website rather than NGINX's 502 error page

Running a NextJS based website on port 8000, deployed and operating in server mode using the yarn start command. The NextJS server is located behind an NGINX server, serving as a reverse-proxy server. Encountering issues with 404 and 5xx error pages. Alt ...

The positioning of NextJS Image seems to be off-kilter

I'm in the process of switching out my regular <img/> tags for NextJS's <Image/> component, but I can't figure out why my images aren't displaying correctly. Here is the original image tag: <div className=" mx-auto ...

Retrieve an image from the public directory in NextJS

I am dynamically saving images in the public folder of my NextJS project. The path to access the image is /public/upload/catalog/{imagename} https://i.stack.imgur.com/CkBu9.png Following the guidance provided in the NextJS documentation on accessing the ...

Leveraging the power of Angular 5 to seamlessly integrate two distinct components on

I am exploring a way to render an additional component on the current page instead of navigating to a new one. Here is my setup: <button mat-button color="primary" [routerLink]="['/tripspath', trip.tripId]" style="cursor: pointer">View Rou ...

Guide on attaching an onclick event to a button created with a string in Next.js?

<div onClick={(event) => this.addToCart(event)}> <ReactMarkdownWithHtml children={this.props.customButton} allowDangerousHtml /> </div> In my current situation, I am facing an issue with the code above. The button is being rendered ...

I created a basic next.js application that utilizes API Routes for handling serverless calls. However, there seems to be an issue with one of the API calls

Submission form: import React, { useState } from 'react'; import { Container, Form, Button } from 'react-bootstrap'; import axios from 'axios'; // ... other imports export default function ContestEntryForm() { const [formDa ...

Implementing Right-to-Left (RTL) support for Shadcn components in Next.js

Currently, I am working with version 14 of the Next.js app. Unfortunately, RTL is not being applied to Shadcn components in my project. In addition, I am utilizing next-intl for supporting multiple languages. Below is a snippet from my layout.tsx file: lay ...

Unable to locate dependencies while testing the react package locally

Recently, I came across this npm package designed for React using Typescript. To debug it locally, I initiated npm link in a new React project but encountered an error: I suspect it may not be reading the packages correctly, but I'm unsure how to re ...