Search code examples
javascriptreactjsreduxflux

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


Solution

  • 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
       });
    }