Mjuice Mjuice - 3 months ago 13
HTML Question

How to only render 25 objects to the screen at a time even though I am mapping over an array containing 1,000 objects using React.js

I am using React and Redux.

In one of my components, I want to map over an array that contains 1000 objects, but only render 25 at a time to the screen.

It would also be ideal to have a button that says "load more" which renders another 25 when a user clicks it.

In my Redux state, I don't mind if there is an array containing 1,000 objects so I don't want to limit the results returned from the database or anything. I just want to control the render method.

Here is my renderProducts() method which I call inside of the my component's main render method:

renderProducts() {

return this.props.allProducts.map(product => {
return (
<div key={product._id} className="col-lg-3 col-md-3 col-sm-3 col-xs-6" id="productThumbnail">
product={product} />

this.props.allProducts is an array that contains the 1,000 objects. How can I only render 25 at a time and implement a function for a button that will increment the number on the screen by 25 at each time?


What about this? This function is a generic one, you pass an array of products you have in your redux state, current page and pageSize, which is how many items are per page. You will need to add UI and extend store to keep track of page and pageSize in the state as well I assume. So eventually they will be available through this.props in your component just like this.props.allProducts are available.

renderProducts(allProducts = [], page, pageSize) {
    const startIndex = page * pageSize;
    const endIndex = Math.min(page * pageSize + pageSize, allProducts.length);

    const viewProducts = allProducts.slice(startIndex, endIndex);

      return viewProducts.map(product =>
          className="col-lg-3 col-md-3 col-sm-3 col-xs-6"