Skip to content
Advertisement

Axios: How to render API item base on spesific child element?

Hi Everyone I am new in ReactJS and also in Axios. I try to get data from Instagram Api and i want to render a Image if image has spesific letter in caption for example if caption has ‘Y’ letter should render on page otherwise not. With my code i render all post from profile but i cant sort the data,the way how i want please help me [![

export default class Home extends React.Component {
    state = {
      posts: []
    }
  
    componentDidMount() {
      
        axios.get("https://graph.instagram.com/me/media?fields=id,caption,media_url,permalink,username&access_token=IGQVJWM3BtaTNEQW9iYXBNZA3JwUU")
        .then(res => {
          const posts = res.data.data;
          this.setState({ posts });
        })
    }
   
 
 

  render() {
    return (
      <div>
       
        {
          this.state.posts
            .map(post =>
            <div className="banner_image">
              <img className="post_img" key={post.id} src={post.media_url} alt="image"/>
           <div className="banner_text">
             <div className="banner_content">
                {
                this.state.posts
                    .map(post =>
                    <h1 className="main_title" key={post.id}>{post.username}</h1>           
                    )
                }
                {this.state.posts
                    .map(post =>
                    <h3 className="main_caption" key={post.id}>{post.caption}</h3>
                
                    )
                }
               
             </div>
           </div>    
           </div>
            )
        }
        
       
         
      </div>
    )
  }
}

][1]][2]

Advertisement

Answer

I would move away from class based react components as the functional style is recommended. You are not doing any sorting within inside your mapping of posts, this is why it is not working. Where you do your this.state.posts.map, I would chain that with a filter to remove the posts you don’t want. So it would be something like this:

this.state.posts
        .filter(post => post.includes('Y'))
        .map(post => ...)
Advertisement