How to dynamically import images in astro.js framework components(react specifically)?

77 views Asked by At

I have a json file containing an array of object's in following format


[

{

name : "foo",

image : "/src/assets/default.webp"

},

{

name : "Jonas",

image : "https://..."

]

Then in my astro file , I am simply importing the json , iterating over it and passing the data to my react components

i.e


---

import data from "../data.json"

---



data.map((e) => {

<Reactcomponent data={data} client:load/>

})



Reactcomponent.jsx


export default function React component({data}) {



return (

<>

<p>{data.name}</p>

<img src={data.image} alt="..." />

</>

)



}

It works just fine in dev mode but in production I have had no luck so far

I can see the images in my dist/_astro folder but they've been renamed and when I inspect the image's in build mode their path remains the same /src/assets/imgname

But in the build there is no src or assets folder and the images also have been renamed

Tbh I am not even sure that the images i am seeing in the dist/_astro folder have something to do with them being used in json

I have read the documentation and it only shows examples of static imports , i have heard about a vite plugin that uses the import() function but it has its own issues , is there any "natural" way to do it or available API for it

1

There are 1 answers

0
Bryce Russell On

You can follow this recipe in the docs for a guide on how to Dynamically Import Images