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>

2 Answers2

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>
Nicolae Olariu
  • 2,487
  • 2
  • 18
  • 30
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(...)
zemil
  • 3,235
  • 2
  • 24
  • 33