nevs nevs
nevs nevs

Reputation: 71

ReactJS showing list of items

I have an array of objects(a list of comments to some item), and I want to display it on the page. But not all of those comments! First 10 for example. And below that list i wanna render some kinda button. And if a user wants to see next 10 comments, he needs to click on that button.

Something like 'show more' in 'Youtube'.

I can render all those comments! But I don't need that. I need to display 10 comments ... each time the button is being clicked.

Can anyone help me please Thanks

Upvotes: 1

Views: 5460

Answers (2)

Md.Estiak Ahmmed
Md.Estiak Ahmmed

Reputation: 1593

from the below code you can get the basic idea of how a loadmore component can be implemented from scratch,

import React, { Component } from 'react';

class Router extends Component {
  constructor() {
    super();
    this.data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 6, 4, 3, 2, 1, 5];
    this.state = {
      count: 5,
      defaultCount: 5,
    };
  }
  handleCount() {
    let count = this.state.defaultCount;
    count = count + this.state.count;
    this.setState({ count });
  }
  render() {
    const count = this.state.count;
    const showData = (item, index) => {
     return ((index < count) ? <li>{item}</li> : '');
    };
 return (
   <div>
     {this.data.map(showData)}
     <a href="#" onClick={this.handleCount.bind(this)}>Load</a>
   </div>
  );
 }
}

what I have done here:

i) take an array with 15 elements;

ii) initialize the state with count and defaultcount

iii) then i have map the data array to show the item on showData function

iV) on the return of showData function i have checed if the index of array element is less than the count variable.

v) and each time you click on loadmore button it will call the handleCount function and increate the count value by defaultCount.

vi) after the count variable updated than more 5 array element will be shown on this example

that's it, i hope you get the basic idea of lodemore

Upvotes: 1

Muhammad Hamada
Muhammad Hamada

Reputation: 725

So let's assume that you have 20 comments in an array

var comments = getComments() // returns list of 20 comments

Then you can use slice to get the first 10 comments, then map them to actual HTML

var commentsAsHTML = comments.slice(0, this.state.limitTo).map(comment => {
   return <li key={comment.id}>{comment.text}</li>
});

To add the "Load more" functionality, we will have limitTo state

limitTo = 10;

And with each "Load more" action, we will increment this limit by 10 for example.

onLoadMore () {
   this.setState({
      limitTo: this.state.limitTo + 10
   });
}

Upvotes: 4

Related Questions