0

can you please help me, how to add "for" loop in this code - the goal is to show only 3 comment from all comments, that are scanned with the .map.

<div>   {data.statement.comments.reverse().map((comment) => (
           
          <div key={comment.id} style={{ marginBottom: 15 }}>
             <strong>
                {comment.user.firstName} {comment.user.lastName}
              </strong>
              <small className={Classes.TEXT_MUTED} style={{ marginLeft: 10 }}>
                {formatCreatedAt(comment.createdAt)}
              </small>
            
                        
            </div>
      ))}

     
        </div>

I tried to put it here -but as I found out it doesn=t work in JSX.

 <div>   {data.statement.comments.reverse().map((comment) => (
           //for Loop
          <div key={comment.id} style={{ marginBottom: 15 }}>
             <strong>
                {comment.user.firstName} {comment.user.lastName}
              </strong>
              <small className={Classes.TEXT_MUTED} style={{ marginLeft: 10 }}>
                {formatCreatedAt(comment.createdAt)}
              </small>
            
                        
            </div>
      ))}

     
        </div>

Or would you recommend to use another way to solve the task?

1

1 Answer 1

1

You can use this, no need for a for loop

data.statement.comments.reverse().slice(0,3).map((comment)...

adding slice here will not change the original array, it will create a new one, it will contain only 3 elements. 0 is where to start the slice and 3 is number of items you want.

To answer your question why for does not work there, try this code.

let a = [1,2,3,4];
let c = a.map(el => {
  console.log(el);
  return el + 1;
})
// c = [2, 3, 4, 5];

as you can see here, Map return a new array, for does not (for is not a function), if you take a closer look at your React code, map will return only JSX, for can't do that since it is not a function.

Here another example

{[1,2,3].map(el => <p> el </p>)}
// is equale to
// <p>1</p><p>2</p><p>3</p>
// which is a valid JSX

so any thing inside {} get excuted and it get replaced by what it return, the map can return, but for can't since it isn't a function, a rule of thumb: you can use ony what return, and if you must use for, use it inside a fucntion and call it from your JSX {}

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.