Not sure how to word this properly so I’ll share a few bits of code.
import {
ClearSkys,
MainlyClear,
PartlyCloudy,
Overcast,
} from "../images/images";
From there I have an object calling those
const [images, setImages] = useState({
0: {
src: { ClearSkys },
disc: "Clear skys",
},
1: {
src: { MainlyClear },
disc: "Mainly Clear",
},
2: {
src: { PartlyCloudy },
disc: "Partly Cloudy",
},
3: {
src: { Overcast },
disc: "Overcast",
}
})
And now I want to call that object to set a image SRC. I try
<img src={images[0].src} />
I don’t call it exactly that way but the way I do gets to the same end point. This doesn’t work for me, any way to call it like this?
CodePudding user response:
You're updating the src
property as an object, so for the obvious reason if you read value as images[0].src
, it won't display the image because src
value is {ClearSkys:"image"}
To fix this,
you should set state without an object, so
src: { ClearSkys }
should be
src: ClearSkys
- while reading, you need
images.0.src
CodePudding user response:
Use a list to store all your images and data related to the image and map your list.
import img1 from "../images/images"
import img2 from "../images/images"
const data = [{
src:img1,
alt: 'text describing image',
},
{
src: img2,
alt: 'text describing image',
}
]
{data.map((item, idx) =>
<img src={item.src} alt={item.alt} />
)}