1

I'm trying to implement "Show More" feature for my comment section in Reactjs but when I click show more it doesn't load the whole array however it removes the show more link. Here is my code:

var CommentBox = React.createClass({
getInitialState: function() {
return {limit:3 ,showMore:false};
},
showMore:function() {
  this.setState({showMore: true, limit: this.props.comments.length});
},
render: function() {
  var cls=[];
  var length=this.props.comments.length;

  if(length >= this.state.limit){
      cls=[];
      for (var i=0;i<this.state.limit;i++ )
          cls.push(this.props.comments[i]);
  }
      return (
    <div className="commentBox">
        <CommentList data={cls} />

        {length> 3 &&!this.state.showMore? <div><a onClick={this.showMore}  >show more</a></div>: null}
    </div>
);
 }
});

making any change to state.comments doesn't affect the view at all.

2
  • 1
    You probably know already that one should not copy props into state. As this usually leads to disaster. I would propose to keep only the number of visible items in the state. Set it to 3 by default and on click on showMore you increase the number of visible items. Commented Jun 6, 2016 at 21:46
  • @pintxo I did what you suggested but it still doesn't change the view [you can see the edit in my code]. I have to mention that this is like a newsfeed and there are many <CommentBox> elements each with a unique key Commented Jun 6, 2016 at 21:56

1 Answer 1

2

This works: http://jsbin.com/ceqisepewu/edit?js,console,output

Compare it with your solution and find the reason it did not work.

Sign up to request clarification or add additional context in comments.

2 Comments

I did exactly what you have here. Initally cls has 3 elements. when I click on show more it changes the cls to 6 elements but it doesn't update the view. I feel like because I have a list of <commentbox> in my newsfeed it doesn't update it. Can it be that?
nvm it is fixed! I changed this.state to this.props in the child element of <commentBox> thanks for the help

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.