-2

I'm new to React.

I know that comments should be received as an object, so I tried using a for...in loop to iterate over them. However, when I attempted to use the for...in loop, I encountered an error:

{for (for Comment in commentData){
  <div className="space-y-6">
    <div className="border-b pb-6">
      <div className="flex items-start gap-4">
        <img
          src={Nodejs}
          alt="Nodejs"
          className="w-10 h-10 rounded-full object-cover"
        />
        <div className="flex-1">
          <div className="flex items-center gap-3 mb-2">
            <h3 className="font-semibold">{Comment.userName}</h3>
            <span className="text-gray-500 text-sm">{Comment.date}</span>
          </div>
          <p className="text-gray-700">{Comment.comment}</p>
        </div>
      </div>
    </div>
  </div>
}}

The error message says:

Unexpected token: did you mean {}?

I believe the issue is with how I am using the for...in loop inside JSX. Can someone explain the correct way to iterate over commentData and why this error occurs? I'd also appreciate an explanation of how JSX handles loops and how to properly fix this issue.

2
  • This question is similar to: Loop inside React JSX. If you believe it’s different, please edit the question, make it clear how it’s different and/or how the answers on that question are not helpful for your problem. Commented Apr 3 at 4:35
  • This doesn't make much sense. for..in iterates an object's keys which wouldn't typically have properties like userName, date and comment. What sort of object is commentData? Commented Apr 3 at 4:37

1 Answer 1

0

You have to use map function to render the commentData, .map() returns a new array of

<div className="space-y-6"> .... </div>

elements, which React can directly render.

for..in does not return.

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.