I am working with a local JSON that has the following structure:
{
"Data": [{
"image": "../Images/project1.png",
}, {
"image": "../Images/project2.png",
},
{
"image": ".../Images/project3.png",
}
]
}
I am mapping this JSON into my component. I want it to show each image from the JSON. This is my component simplified:
import data from '../Data/Projects.json'
function ProjectsMenu(props){
return(
{data.Data.map(s =>{
return(
<img src={s["image"]} alt={s["image"]}></img>
)
})}
}
This code doesn't load the images into the website. If I manually import the images it does work:
import Img from '../Images/present.png'
...
<img src={Img} alt={s["image"]}></img>
I want to be able to import them dynamially so that if the JSON is modified, I don't have to go back and add the image import to the code.
It does not matter if yow pics are at Facebook, google or local host; it. Is a client/server architecture that uses the same protocol tcp/ip.
So as your are using cra the folder of yow pics need to be inside of your public folder, next to your index.html is
To fetch the images
<img src=“/images/image-name.png” />
import data from '../Data/Projects.json'
function ProjectsMenu(props){
return(
{data.Data.map(s =>{
return(
<img src={require(s["image"])} alt={s["image"]}></img>
)
})}
}
When we use dynamically then s["image"] will not load the image, we need to load the image manually by require(s["image"]).
If it did't work then try import(s["image"]).