2

I just started to learn React and I am trying to figure out how to find a specific value I am looking for. Just like you have the each.do method in Ruby and you can iterate through an array, I'm trying to do that with React.

class Gallery extends React.Component {
  render () {
    // debugger;
    return (
      <div>
      <img> {this.props.gallery.thumbnail_url} </img>
      </div>
    )
  }
}

I am trying to access the thumbnail._url and when using the debugger, I am not able to access all the objects and images. I thought of this.props.gallery.object.thumbnail_url and other ideas but I am not really sure of the best way! debugger information

2 Answers 2

3

Use Array.prototype.map() to map the data to react elements. Not that elements rendered in a loop require a unique identifier (keys), to make rerendering list more performant.

class Gallery extends React.Component {
  render () {
    const { gallery = [] } = this.props; // destructure the props with a default (not strictly necessary, but more convenient) 

    return (
      <div>
      {
       gallery.map(({ id, thumbnail_url }) => (
         <img key={ id } src={ thumbnail_url } />
       ))
      }
      </div>
    )
  }
}
Sign up to request clarification or add additional context in comments.

Comments

1

You can do something like this:

class Gallery extends React.Component {
  render () {
    // initialize 'images' to empty array if this.props.gallery is undefined
    // other wise 'images.map' will throw error
    const images = this.props.gallery || []; 

    return (
      <div>
        {images.map((image, index) => <img src={image.thumbnail_url} key={index} />)}
      </div>
    )
  }
}

You may have noticed the prop key={index}. If you omit that, you will see a warning:

Each child in an array or iterator should have a unique "key" prop

Actually it is not passed to the component as prop but is used by React to aid the reconciliation of collections. This way React can handle the minimal DOM change.

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.