#dynamic <Image> component

14 messages · Page 1 of 1 (latest)

simple badger
#

How can i change this example from docs

---
import { Image } from 'astro:assets';
import myImage from "../assets/my_image.png"; // Image is 1600x900
---

<!-- `alt` is mandatory on the Image component -->
<Image src={myImage} alt="A description of my image." />

into dynamic like:

const { src, alt, width, height} = Astro.props;
const myImage = getImage({
    src: src,
    width: width,
    height: height
});

i get an error:
UnsupportedImageFormat: Received unsupported format undefinedfromundefined. Currently only jpeg, jpg, png, tiff, webp, gif are supported for optimization.

visual oriole
simple badger
#

My src comes from JS data list, it contains images in assets folder (so they are local). It is string.

visual oriole
simple badger
#

No, my list is pure JS list, it is not Content Collection.

#
export const carData = {
  items: [
    {
      title : 'Mercedes',
      src: 'assets/cars/mercedes.jpg',
halcyon violet
#

You'll need to replace the src in your list with an import

#

For local images, images needs to be imported so we can statically know to add them into the final result

#

It's a bit annoying, but it is necessary due to SSR

#

If you don't need optimization, you can alternatively move the images to public and then you'll be able to use strings

simple badger
#

Can you show me what is the syntax for inline import?
Like:

src: import('assets/cars/mercedes.jpg'),
halcyon violet
#

Yeah, that's fine

#

Inline imports are async though, so make sure to await it eventually

visual oriole
#

and that the paths are relative to the file you are importing from.

That said, you can also use the ~/assets alias and not worry about that 😊

If you don't want to deal with the async nature of inline imports you can import them at the start of the file.

import MercImage from '~/assets/cars/mercedes.jpg';

export const carData = [{
  src: MercImage,
}];