Categories
React Answers

How to Map Only a Portion of an Array to Components in a React Component?

Spread the love

Sometimes, we want to map only a portion of an array to components in a React component.

In this article, we’ll look at how to map only a portion of an array to components in a React component.

Map Only a Portion of an Array to Components in a React Component

To map only a portion of an array to components in a React component, we can use the JavaScript array’s filter method to return an array of the items we want to map before calling map.

For instance, we write:

import React from "react";

export default function App() {
  const feed = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11];

  return (
    <div>
      {feed
        .filter((item) => item <= 5)
        .map((filteredItem) => (
          <p key={filteredItem}>{filteredItem}</p>
        ))}
    </div>
  );
}

to create the feed array.

And we want to display the first 5 entries from feed.

To do this, we call filter with (item) => item <= 5 to return the first 5 elements.

Then we call map with a callback to return p elements with the content of the elements to display them on the screen.

Now we see:

1

2

3

4

5

on the screen

Conclusion

To map only a portion of an array to components in a React component, we can use the JavaScript array’s filter method to return an array of the items we want to map before calling map.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *