0

I want to change Check All Button inner text to the Uncheck All after all the checkboxes will be checked. Here's my code. Any suggestions?

 checkAllCheckBox = () => {
    let {todos} = this.state
    let newArray = [...todos]
    if (newArray.length !==0) {
        newArray.forEach(item => {
            if (item.checked === true) {
                item.checked = false
            } else {
                item.checked = true
            }
            this.setState({todos: newArray})
        })
        console.log('----todos', todos)
    }
}

render() {


    const {itemsPerPage, currentPage, todos} = this.state;

    console.log('--------todos', todos);

    const end = currentPage * itemsPerPage
    const start = end - itemsPerPage
    const currentItems = todos.slice(start, end);
    return <div className={"App"}>
        <div className="App-header">
            <h2>Welcome to To-Do List App</h2>
        </div>
        <input ref={this.inpRef} onKeyPress={this.handleKeyPress} name={''} type='text'/>
        <button onClick={() => this.addItem()} className={'btn btn-primary'}>Add</button>
        <button  onClick={() => this.checkAllCheckBox()}
          className={'btn btn-primary'}>Check All</button>
        <ul>
            {
                currentItems.map(todoItem => {
                    return <ListItem
                        key={todoItem._id}
                        todoItem={todoItem}
                        deleteItem={this.deleteItem}
                        editItem={this.editItem}
                        submitEdit={this.submitEdit}
                        deleteData = {this.deleteData}
                    />
                })
            }
            <div>
                {this.renderPagination()}
            </div>
        </ul>
    </div>
};
}

export default App;

1 Answer 1

2

Replace Check All with {this.state.todos.every(todo => todo.checked) ? "Uncheck All" : "Check All"}.

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

2 Comments

Also I'm new to the react and i just want to make sure , I'm not mutating state in checkAllCheckBox function right?
No you're not, that works, though I would recommend using map instead of forEach to simplify the logic.

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.