Sanity.io and using images with next/image extension glitch

Hello everyone, I'm excited to join Stack Overflow for the first time. Currently, I am working on a project using Next.js with Sanity as my headless CMS. I have come across what appears to be a TypeScript type issue. Here is the link to the code on GitHub: https://github.com/GabrielPedroza/e-commerce/blob/main/components/Product.tsx

<Image src={urlFor(image && image[0]!)} />

import imageUrlBuilder from "@sanity/image-url"
import { SanityImageSource } from "@sanity/image-url/lib/types/types"

export const client = sanityClient({
    projectId: "gz95qrem",
    dataset: "production",
    apiVersion: "2022-04-27",
    useCdn: true,
    token: process.env.NEXT_PUBLIC_SANITY_TOKEN, // for security purposes
})

const builder = imageUrlBuilder(client)

export const urlFor = (source: SanityImageSource) => {
    return builder.image(source)
} 
Type 'ImageUrlBuilder' is not assignable to type 'string | StaticImport'.
  Property 'src' is missing in type 'ImageUrlBuilder' but required in type 'StaticImageData'.ts(2322)
image.d.ts(19, 5): 'src' is declared here.
image.d.ts(29, 5): The expected type comes from property 'src' which is declared here on type 'IntrinsicAttributes & Omit<DetailedHTMLProps<ImgHTMLAttributes<HTMLImageElement>, HTMLImageElement>, "ref" | ... 4 more ... | "loading"> & { ...; }'

Server Error
Error: Image is missing required "src" property. Make sure you pass "src" in props to the `next/image` component. Received: {}
Call Stack
Image
node_modules/next/dist/client/image.js (160:18)
renderWithHooks
file:///Users/gabrielpedroza/Code/e-commerce/node_modules/react-dom/cjs/react-dom-server.browser.development.js (5448:16)
renderIndeterminateComponent
file:///Users/gabrielpedroza/Code/e-commerce/node_modules/react-dom/cjs/react-dom-server.browser.development.js (5521:15)
renderElement
file:///Users/gabrielpedroza/Code/e-commerce/node_modules/react-dom/cjs/react-dom-server.browser.development.js (5736:7)
renderNodeDestructive
file:///Users/gabrielpedroza/Code/e-commerce/node_modules/react-dom/cjs/react-dom-server.browser.development.js (5875:11)
renderNode
file:///Users/gabrielpedroza/Code/e-commerce/node_modules/react-dom/cjs/react-dom-server.browser.development.js (6009:12)
renderHostElement
file:///Users/gabrielpedroza/Code/e-commerce/node_modules/react-dom/cjs/react-dom-server.browser.development.js (5433:3)
renderElement
file:///Users/gabrielpedroza/Code/e-commerce/node_modules/react-dom/cjs/react-dom-server.browser.development.js (5742:5)
renderNodeDestructive
file:///Users/gabrielpedroza/Code/e-commerce/node_modules/react-dom/cjs/react-dom-server.browser.development.js (5875:11)
renderNode
file:///Users/gabrielpedroza/Code/e-commerce/node_modules/react-dom/cjs/react-dom-server.browser.development.js (6009:12)

I have tried using a string or using ts-ignore to remove the error, but this approach doesn't work for me as I'm utilizing Sanity. As a temporary workaround, I have resorted to using the regular img tag with a ts-ignore to make it function. I have sought help in the official Next discord server and searched through documentation, but unfortunately, I haven't found a solution yet.

Answer №1

I encountered a similar issue...

The workaround I found was to include the following line before calling the src Image:

src={urlFor(image).url()};

Additionally, in my schema files, I updated the type of "image" to "SanityImageSource"

Best regards!

Answer №2

Discovered a clever fix:

const source = generateUrl(image && image[0]).url()

<div style="position: relative;">
    <Image loader={() => source} src={source} layout='fill' />
</div>
`` Wrap the Image component in a div tag and ensure it has `position: relative;` so that layout='fill' can function correctly for creating responsive images

Answer №3

My current setup involves using Next13 and sanity.io for pulling images, with deployment on Vercel. Special thanks to @javiRelax for the helpful hint that made it all come together. This is how I've implemented it:

     {Images.map((array, index) => {         
        return(           
          <Image
          src={urlFor(array.imgUrl).url()}
          alt={array.alt}
          key={index}
          width="100"
          height="100"
          unoptimized={true} 
          />
        );
      })}
              

After encountering some issues, I found that adding

unoptimized={true}

was necessary for the functionality to work as intended.

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

DuplicateModelError: Unable to duplicate model after it has been compiled, React.js, MongoDB, TypeScript

In the early stages of developing an application using Next.js, Mongoose, and Typescript, I encountered a persistent issue. Whenever I attempt to send a request through Postman after clicking save, it fails, displaying the error message: OverwriteModelErr ...

Learn how to successfully import a webp image into a React TypeScript project

I have looked everywhere for the answer, but I can't seem to find it When trying to import a *.webp image in typescript, you need to create a declaration file, like declaration.d.ts The declaration file should contain something similar to the foll ...

Select a random class from an array of classes in JavaScript

I have a collection of Classes: possibleEnemies: [ Slime, (currently only one available) ], I am trying to randomly pick one of them and assign it to a variable like this (all classes are derived from the Enemy class): this.enemy = new this.possibleEn ...

Helping to maintain compatibility with previous URL structures using Next.js

Exploring a new Next.js project, I find myself in a situation where I must support legacy URLs without the ability to implement 301 redirects. The URLs I need to accommodate look like www.dan.com/foo/bar/slug As of now, my folder structure is arranged as ...

Determining when to include @types/packagename in React Native's dev dependencies for a specific package

Just getting started with React Native using typescript. Take the package vector icon for example, we need to include 2 dependencies: 1. "react-native-vector-icons": "^7.1.0" (as a dependency) 2. "@types/react-native-vector-icons": "^6.4.6" (as a dev ...

[deactivated]: Modify a property's value using a different component

One of the requirements for my button is that it should be disabled whenever the callToActionBtn property is true. match-component.html <button [disabled]="callToActionBtn" (click)="sendTask()>Send</button> match-component.ts public callToA ...

I want to search through an array of tuples to find a specific value in the first index, and if there is a match, I need to return the value in the second index of the matching tuple

I am dealing with an array of tuples: var tuparray: [string, number][]; tuparray = [["0x123", 11], ["0x456", 7], ["0x789", 6]]; const addressmatch = tuparray.includes(manualAddress); In my function, I aim to verify if the t ...

Specify the title attribute by using a language-based string

Can the title attribute content on an image be defined as a language string that can be overridden in a multilingual website? I am considering following this format: <img title="tooltip_mod".....> Creating a tooltip_mod INI file that defi ...

Error encountered when using withRouter together with withStyles in Typescript on ComponentName

Building an SPA using React with Typescript and Material UI for the UI framework. Stuck on a recurring error across multiple files - TS2345 Typescript error: Argument of type 'ComponentType<Pick<ComponentProps & StylesProps & RouteCompo ...

How to eliminate all special characters from a text in Angular

Suppose I receive a string containing special characters that needs to be transformed using filter/pipe, with the additional requirement of capitalizing the first letter of each word. For instance, transforming "@!₪ test stri&!ng₪" into "Test Stri ...

Learn the steps to dynamically show a navbar component upon logging in without the need to refresh the page using Angular 12

After logging in successfully, I want to display a navbar on my landing page. Currently, the navbar only shows up if I reload the entire page after logging in. There must be a better way to achieve this without a full page reload. app.component.html <a ...

Cease the interval once the array is devoid of elements

I'm currently working on simulating typing effects for incoming server messages by adding an interval to the output. Here's what I have so far: const stream = interval(1000) .pipe( map((): Message => { return messages.pop(); }) ); ...

Tips for utilizing Redux toolkit dispatch within Next.js when using SSG or SSR

I've been struggling for a while to resolve my problems with using Hook like useDispatch in either getStaticProps or getServerSideProps. I'm utilizing redux-toolkit for state management and also working with Next.js, but encountered an error when ...

"Concealing the primary layout in Next.js 14: A step-by-step

Within NextJs 14, I am utilizing the App router. My main layout contains a navbar and footer, however, I aim to hide this layout specifically on my admin page. How can I achieve this in the most efficient manner possible? ...

The anchor for the circular image is oversized

Currently, I have a PHP code that displays a user's profile picture, and when clicked, it takes them to their own profile. The image is displayed correctly, and the link works fine. However, there seems to be an issue with the area covered by the anch ...

Encountered an issue while attempting to assign a value to a property that is declared as [key in keyof T]

I am currently working on implementing a function that selects specific properties of an object. Here is the current function: const project = function<T>(object: T, projection: Projection<T>): Partial<T> { throw new Error("not imple ...

The image located at src "/_next/static/media/..." has a legacy prop called "layout". Don't forget to run the codemod to update it

Here is the code I am working on: <div className={`w-5 h-5 relative flex-shrink-0 ${additionalClasses}`}> <Image src={icon} layout="fill"/> </div> When I check the console, I see this message: I was surprised to find a war ...

How can I access the locale in the document component in Next.js?

Is there a way to set the locale in the google maps script dynamically, like so: <script defer src={`https://maps.googleapis.com/maps/api/js?key=key&libraries=places&language=${locale}`}/> I am having trouble accessing the locale in the Docu ...

Why are my styled components not being utilized on my components?

Trying to apply styling to my components with 'styled-components' but it's not working. Attempted to include styling in the same file. Referenced the documentation on styling normal react components. Code snippet : // File containing the c ...

Transferring data from the server to the client side in Next JS with the help of getInitialProps

I am currently developing an application using nextJS. Within server/index.ts, I have the following code: expressApp.get('/', (req: express.Request, res: express.Response) => { const parsedUrl = parse(req.url, true); const { query } = ...