user6002037
user6002037

Reputation:

React - show photo if media type is a photo

I am trying to use a loop in jsx which is working.

I am making a call to an API which returns a list of instagram posts. This works fine, however some posts have both videos and photos linked to them, which is causing the issue.

If the post media type is a video then the type === 'video' else it is type === 'photo'. I have written this logic below, and when I console.log(photo) I get a link to the url of each photo, however, <img src={photo} /> doesn't show the photo on the page, but instead shows } where the photo should be.

Can anyone advise me how I can fix this issue? Let me know if any further information is required. As far as i am aware it is because photo in the map function is in a different scope?

render: function() {
   var photo;
   var instagramPostList = this.props.posts.map(function(post, index){
     return(
        <li key={index} className='card'>
           <div className='insta-pic'>  
             {
               post.media.map(function(photo, index){
                  if(photo.type === 'photo') {
                     photo = post.media[index].url;
                        console.log(photo);
                   }
                })
              }
              <img src={photo} />
            }
           </div>
        </li>
    )
   })
   return (
      <div>
         <ul>{instagramPostList}</ul>
      </div>
    )
  }

In an attempt to access photo outside the map function I have tried add this which was also unsuccessful.

post.media.map(function(photo, index){
    if(photo.type === 'photo') {
        photo = post.media[index].url;
        console.log(photo)
    }
}, this);

Upvotes: 0

Views: 294

Answers (1)

Jyothi Babu Araja
Jyothi Babu Araja

Reputation: 10292

Try this

{
  post.media.map(function(photo, index){
    return photo.type === 'photo' && (<img src={photo.url} />)
  })
}

inside your

<div className='insta-pic'>  

</div>

You are using one extra } and your <img src={photo.url} /> is out of the .map iterator.

Upvotes: 5

Related Questions