0

I am trying to iterate an array inside another loop in my react app. I have a json file that contains data that looks like this:

[
    {
        "id":"0001",
        "photos":[
            "IMG_9239.JPG",
            "2019-01-07.jpg",
            "IMG_9261.JPG"
        ]
    },
    {
        "id":"0002",
        "photos":[
            "IMG_9239.JPG",
            "2019-01-07.jpg",
            "IMG_9261.JPG"
        ]
    },
    {
        "id":"0003",
        "photos":[
            "IMG_9239.JPG",
            "2019-01-07.jpg",
            "IMG_9261.JPG"
        ]
    }
]

And this is my react component:

const ListItems = ({data}) => {
    return (
        <div id="items-container">
            {data.map( item => (
                <p>{item.id}</p>
                //iterate the [photos] array in an img tag
                //<img src ="photo" />
            ))}
        </div>
    )

}

I am trying {item.photos.map....} but it seems like it's not a valid syntax. Can you please help?

2
  • Can you show the error? Commented May 5, 2020 at 3:16
  • Unexpected token, expected "," Commented May 5, 2020 at 3:19

1 Answer 1

3

Multiple JSX elements require a parent, or at least a psuedo-parent. Here, you can use a fragment <> as the parent of what gets returned from the .map callback, enclosing both the <p> and the <img>s:

const ListItems = ({data}) => {
    return (
        <div id="items-container">
            {data.map( item => (
                <>
                    <p>{item.id}</p>
                    {item.photos.map(({ src }) => <img src={src}></img>}
                </>
            ))}
        </div>
    )
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.