0

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 ? }/>

)))}
3
  • Try src={`http:localhost:8000/pictures/${photo} /> Commented Jan 28, 2022 at 14:27
  • How do you initialize/update your pictures array? Commented Jan 28, 2022 at 14:37
  • Question was edited, any comment/answer mentioning "photo" is out of date. Commented Jan 28, 2022 at 14:39

2 Answers 2

2

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}`}/>
 ))}
Sign up to request clarification or add additional context in comments.

5 Comments

When I do that, the app send me an error : Cannot read property of undifined (reading 'map') If it can help, I get the array of the pictures names with an axios request into a useEffect. Maybe the problem comes from that ?
I can assume that you are updating the state for the pictures. If that is the case, the initial state should also be an Array. So you may write const [pictures, setPictures] = useState([])
Yes, I forgot to make it an array. Now I have another problem, I have empty squares instead of the images (like picture not found). I think it is because the names in the array are between simple quote and the quote are passed into the URL ? I tried a .replace function to remove them but it doesn't work.
You only need to put it as an empty array. If you could share the whole code with me, I can help you better.
I made an answer below with the code, to make it easier to read for you
0

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

6 Comments

It will be ${photo} not ${picture}
Won't work, the variable name is photo, not picture
I have edited my post to make it more clear, picture is everywhere now. But now, the app crash and says "cannot read property of undifined
@ManirajMurugan it is picture not photo
@LucasClaude, Now you have edited the question, but before that you have mentioned it as photo right?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.