Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ReactJs how to show list with load more option

I am tring to show todo list with load more option. I am appling limit.Limit is apply to list.But when i add loadmore()function. then i get error this.state.limit is null Wher i am wrong.Any one can suggest me. here is my code todoList.jsx

var TodoList=React.createClass({
    render:function(){
    var {todos}=this.props;
    var limit = 5;

    function onLoadMore() {
        this.setState({
            limit: this.state.limit + 5
        });
    }
    var renderTodos=()=>{
            return todos.slice(0,this.state.limit).map((todo)=>{
                return(
                        <Todo key={todo.todo_id}{...todo} onToggle={this.props.onToggle}/>
                );
            });

    };

    return(
        <div>
            {renderTodos()}
            <a href="#" onClick={this.onLoadMore}>Load</a>
        </div>
        )
}
});
module.exports=TodoList;
like image 766
Sweety Avatar asked May 19 '17 13:05

Sweety


1 Answers

Changes:

1. First define the limit in state variable by using getInitialState method, you didn't define the limit, that's why this.state.limit is null.

2. Define all the functions outside of the render method.

3. Arrow function with renderTodos is not required.

4. Use this keyword to call the renderTodos method like this:

{this.renderTodos()}

Write it like this:

var TodoList=React.createClass({

    getInitialState: function(){
        return {
            limit: 5
        }
    },

    onLoadMore() {
        this.setState({
            limit: this.state.limit + 5
        });
    },

    renderTodos: function(){
        return todos.slice(0,this.state.limit).map((todo)=>{
            return(
                <Todo key={todo.todo_id}{...todo} onToggle={this.props.onToggle}/>
            );
        });
    };

    render:function(){
        var {todos} = this.props;
        return(
            <div>
                {this.renderTodos()}
                <a href="#" onClick={this.onLoadMore}>Load</a>
            </div>
        )
    }
});
like image 198
Mayank Shukla Avatar answered Oct 12 '22 19:10

Mayank Shukla