Home > Mobile >  React render instagram feeds and loop comments/likes
React render instagram feeds and loop comments/likes

Time:10-28

I"m trying to render comments with likes and loop them. please see image on demo.

  • All of this comes form data.json
  • How can I loop all comments? I have only one displayed. What am I missing here?

Sorry I'm trying my best here with react as I'm quite a beginner.

my index.js

import React from "react";
import styles from "./styles";
 
 
const Posts = (props) => {
  const { data } = props;
  const comments = data.edge_media_to_comment.edges[0].node.text
  const locationName = data.location.name
  const username = data.owner.username 
  const id = data.id 
  const url = `https://www.instagram.com/${data.owner.username}`
  const likes = data.edge_media_preview_like.count
 

  return (
    <>

  <a href={url} rel="noopener noreferrer" target="_blank" key={id}>
    <img src={data.owner.profile_pic_url} />
  </a>
        <span>{locationName}</span> 
        <a href={url} rel="noopener noreferrer" target="_blank" key={id}>@{username}</a>
        <p>{username}</p>
        
        <hr />
 
        <ul> 
            <li> 
                {comments !== null ? comments.toLocaleString() : 0}
            </li> 
            <li className="post-item-likes"> 
                {likes !== null ? likes.toLocaleString() : 0}
            </li>
        </ul>
        <hr />
 
     </>
  );
};

export default Posts;

CodePudding user response:

In your Post component need to use data.comments from props and use .map method for render multiple comments instead of comments.toLocaleString()

Example:

import React from "react";

const Posts = (props) => {
  const { data } = props;

  console.log('007',data);

  return (
    <>
      <img src={data.owner.profile_pic_url} />
      <span>{data.location.name}</span>
      <a href="" target="_blank">
        @{data.owner.username}
      </a>
      <p> {data.owner.username}</p>
      <hr />
      <div>
      {data?.comments?.map(comment => {
        return (<div>
          {comment?.text} - {comment?.likeCount}
        </div>)
      })}
      </div>
    </>
  );
};

export default Posts;

CodePudding user response:

You need to map through the comments array and for each comment return the text and likes.

Declare comments - below const { data } = props;:

const comments = data.comments;

In return add this:

<ul>
     {comments.map((comment) => (
       <li>
         {comment.text} - {comment.likeCount}
       </li>
    ))}
</ul>
  • Related