#How do I use the experimental assets api with undefined dynamic images

4 messages · Page 1 of 1 (latest)

shell fjord
#

I am trying to import images dynamically, but in some cases the image source will be undefined.

My code looks like this:

        src={import((`../assets/images/team-profiles/${member.profile.filename}.jpg`))}
        width={400}
        height={400}
        alt=""
    /> : "no image"}```

Even though it should not be rendering the `<Image/>` component when the image filename is undefined, it still gives me this error:

```Received unsupported format undefined from undefined. Currently only jpeg, jpg, png, tiff, webp, gif are supported for optimization.```
somber cobaltBOT
#

Hi @shell fjord. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:

#

It seems like you're trying to import images dynamically using the Astro <Image /> component. However, the error you're encountering is related to an unsupported format. Based on the information provided in the extracts, I can suggest a possible solution.

First, let's update your code to use a dynamic ESM import with a conditional rendering:

{member.profile?.filename ? (
  <img
    src={(await import(`../assets/images/team-profiles/${member.profile.filename}.jpg`)).default}
    width={400}
    height={400}
    alt=""
  />
) : (
  "no image"
)}

This code snippet uses a dynamic ESM import and the standard <img> tag instead of the Astro <Image /> component. It should only attempt to import the image when member.profile.filename is defined, avoiding the error you're encountering.

Keep in mind that this approach is recommended only if you prefer dynamic ESM imports over static ones. You can find more information about this in the Legacy v0.x Upgrade Guide (https://docs.astro.build/en/guides/upgrade-to/v1#tip-if-you-dislike-static-esm-imports-astro-also-supports-dynamic-esm-imports).

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:

Astro Documentation

Archived guide documenting changes between pre-v1 versions of Astro

#

@shell fjord kapa.ai is still learning and improving, please let us how it did by reacting below