0

My question is regarding how to iterate partially through an array in React JSX. Instead of calling .map and iterating through all the items in profile.categories, I only want to display the first five items in the array. I currently have the following code:

<div className="categories">
   {profile.categories.map(category => (
       <div
         className="profile-categories"
         style={{ float: "left" }}
       >
         {category}
       </div>
     ))}
 </div>
0

2 Answers 2

3

Use slice directly on profile.categories, like so:

<div className="categories">
{profile.categories.slice(0, 5).map(category => (
   <div
     className="profile-categories"
     style={{ float: "left" }}
   >
     {category}
   </div>
 ))}
 </div>
Sign up to request clarification or add additional context in comments.

Comments

0

Just use slice with map:

profile.categories.slice(0, 5).map(...)

Also you can add method for getting some count of categories in component:

getFirst(count) {
  return profile.categories.slice(0, count);
}

// and then in render:
this.getFirst(5).map(...)

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.