0

I'm not sure how to render an object from an array into react.

My MongoDB schema is

const postSchema = new mongoose.Schema({
    userID: { type: String },
    dateTime: { type: Date, default: Date.now },
    comments: [{
        userID: { type: mongoose.Schema.Types.ObjectId, ref: 'User' },
        likes: { type: Number, default: 0 },
    }],
})

In react, I want to render just dateTime and likes.

function Post(post) {
    const {dateTime, likes } = post;
    return (
        <tr>
            <td>
                {dateTime}
            </td>
            <td>
                {likes}
            </td>
         
        </tr>
    );
  }

dateTime works fine and renders the data but Likes does not render anything. I have tried {comments.likes} but an error shows: Error: Objects are not valid as a React child (found: object with keys {dateTime, likes}). If you meant to render a collection of children, use an array instead.

function Post(post) {
    const {dateTime, comments.likes } = post;
    return (
        <tr>
            <td>
                {dateTime}
            </td>
            <td>
                {comments.likes}
            </td>

        </tr>
    );
  }

Does anyone know how to render "likes" so I can display them in react? Thank you so much in advance.

1 Answer 1

1

comments is an Array of object . So we need to iterate over to render the likes. Assuming you need to show the likes of the Post by summing up all the likes within the comments .

const {dateTime, comments} = post;

const getLikes = () => {
  const likes = comments.reduce((totalLikes, comment) =>  totalLikes + comment.likes , 0);
  return likes;
}

return (
  <tr>
      <td>
          {dateTime}
      </td>
      <td>
          {getLikes()}
      </td>
  </tr>
);
Sign up to request clarification or add additional context in comments.

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.