I receive an array like this from the backend :
['test.jpg', 'test2.jpg']
I put it into a React state named pictures.
What I need to do is to map on it, and for each picture name in the array, create an img with that name as variable in the path like this :
{pictures.map((picture) => (
<img
className="picture"
src={`http:localhost:8000/pictures/${ WHAT DO I NEED TO WRITE HERE ? }/>
)))}
CodePudding user response:
The first argument from the map function refers to each item in your array, so name it whatever you want and you get the item from the array.
Since you have named it picture, the name of the each item is now picture
Briefly, you can put picture in the space as:
{pictures.map((picture) => (
<img
className="picture"
src={`http:localhost:8000/pictures/${picture}`}/>
))}
CodePudding user response:
In this case you would just need to add http:localhost:8000/pictures/${picture}
Of course this will only work as long as there is an image with a matching name on port 8000
CodePudding user response:
The whole code :
import "./Gallery.css";
import axios from "axios";
import { useState, useEffect } from "react";
export default function Gallery() {
const [pictures, setPictures] = useState([]);
useEffect(() => {
axios
.get("http://localhost:8000/pictures")
.then((res) => {
setPictures(res.data);
});
}, []);
console.log(pictures);
return (
<div id="galleryContainer">
{pictures.map((picture) => (
<div className="pictureContainer">
<img
className="picture"
src={`http://localhost:8000/pictures/${picture}`}
alt={""}
/>
</div>
))}
</div>
);
}
