Skip to content

Using Dynamic Filename Props in Astro Images

Published:

Are you trying to pass an image file name as a prop in Astro? A quick example of a dynamic image file is this:

const imageFile = 'example.jpg';
---
<Picture src={import(`../images/${imageFile}`)} ... >

You would expect it to work, wouldn't you? But it doesn't! There are two fixes for this, one for Astro 2.0 and up versions, and one for Astro 1.X versions.

Astro 2.0+ fix: add a hardcoded file type. Example:

const imageFile = 'example';
---
<Picture src={import(`../images/${imageFile}.jpg`)} ... >

See how the file name now has the .jpg hardcoded into it? It is a requirement by Vite 4, the Vite version that Astro uses.

Here's the solution for older astro versions, so Astro versions 1.X:

const imageFile = 'example';
---
<Picture src={import(`../images/thumbnail-${imageFile}.jpg`)} ... >

Notice the hardcoded word "thumbnail" before the dynamic file name and the hardcoded JPG file type. With the Vite 3 that Astro uses, dynamic image imports need a common file name patter, which means that the files must start with the same word - in this case I chose the word "thumbnail".

I hope these helped you!