Categories
React Answers

How to map only a portion of an array with React?

Spread the love

Sometimes, we want to map only a portion of an array with React.

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

How to map only a portion of an array with React?

To map only a portion of an array with React, we can use the JavaScript array’s slice method.

For instance, we write:

import React, { useState } from "react";

const items = ["Item A", "Item B", "Item C", "Item D"];

export default function App() {
  const [showMore, setShowMore] = useState();

  return (
    <div>
      <button onClick={() => setShowMore((s) => !s)}>toggle show more</button>
      {showMore
        ? items.map((it) => <p key={it}>{it}</p>)
        : items.slice(0, 2).map((it) => <p key={it}>{it}</p>)}
    </div>
  );
}

We have a button that toggles the showMore state when it’s clicked.

If showMore is true, then we call items.map with a callback to render all the content of items in their own p elements.

Otherwise, we call slice with 0 and 2 to only return an array with the first 2 elements.

And we call map with a callback to render each item.

Therefore, when we click toggle show more, we should see the list toggle between 2 and 4 items.

Conclusion

To map only a portion of an array with React, we can use the JavaScript array’s slice method.

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 *