1

I have some JSON that I am looping over in my React app. Within the JSON I am looping over I have an object which contains multiple images. I would like to loop through these images and render each of them as well. Here is what I tried:

const locations = [
  {
    "name": "First Location",
    "photos": [
      {
        "url": "http://placehold.it/250x250",
      }, {
        "url": "http://placehold.it/250x250",
      }
    ]
  }, {
    "name": "Second Location",
    "photos": [
      {
        "url": "http://placehold.it/250x250",
      }, {
        "url": "http://placehold.it/250x250",
      }
    ]
  }
]

const element = (
  <div className="community-list">
    {locations && locations.map((location, index) => (
      <div key={index} className="location">
        <h2>{location.name}</h2>
        {Object.keys(location.photos).map(function(key) {
          return <img src="{location.photos[url]}" />;
        })}
      </div>
    ))}
  </div>
);
ReactDOM.render(element, document.getElementById('mountNode'));

However this gives me 2 broken images

2 Answers 2

2

The actual problem, There is an extra double quotes for img tag. Remove the double quotes enclosing the curly braces. Your images will be displayed

<img src={location.photos[url]} />
Sign up to request clarification or add additional context in comments.

Comments

1

What you wanna do is this:

const locations = [
  {
    "name": "First Location",
    "photos": [
      {
        "url": "http://placehold.it/250x250",
      }, {
        "url": "http://placehold.it/250x250",
      }
    ]
  }, {
    "name": "Second Location",
    "photos": [
      {
        "url": "http://placehold.it/250x250",
      }, {
        "url": "http://placehold.it/250x250",
      }
    ]
  }
]

const element = (
  <div className="community-list">
    {locations && locations.map((location, index) => (
      <div key={index} className="location">
        <h2>{location.name}</h2>
        {location.photos.map(function(photo) {
          return <img src="{photo.url}" />;
        })}
      </div>
    ))}
  </div>
);
ReactDOM.render(element, document.getElementById('mountNode'));

What this would do is iterate through the photos array of a location, and then use the url node of the photo object.

2 Comments

Thank you for the response, between your answer and Gangadhar's answer above I was able to get it working! Turns out you don't need to enclose the url in quotation marks.
Oh yeah. That's one way of doing it too. Alright man, good luck on your app!

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.