I'm recently working with react.js and want to create a todo-app. In my state, I write the following:
this.state={tasks: [ ["Eat",true],
["Sleep",false],
["Read",true]]}
This state will be rendered into different checkboxs.
And in the content I want to render:
<div className="todo-app__total">{Num} Left</div>
The Num
here is the variable I want to demonstrate how many items are there that are still not completed (false). In the above case, Num
=2.
The other buttons are functioning properly now, so the state may dynamically change through time, but I hope that Num
can change simultaneously when the state has been updated.
How do I collect the number of true members, while they are not in the same array (In same column)?
CodePudding user response:
Assuming you have an object like,
{name: 'Sleep', completed: false}
you can check as follows,
items.filter(item=>item.completed == true)?.length
CodePudding user response:
If you looking for an easy solution, just use the following
<button>{this.state.tasks.filter(task=>task[1] == true)?.length}</button>
But I am not sure whether that will work, you should create another state, not necessarily, but it's clean and easy to understand. Also, you should have an array of objects.
this.state={
tasks: [
{name: "Eat", completed: true},
{name: "Sleep", completed: false},
{name: "Read", completed: true}
],
done: 2,
}
This is the right way to do it. Then just read this from the button.
<div className="todo-app__total">{done} Left</div>
And after you complete a todo, just increase or decrease the done value like the following.
// After completing a todo
this.setState({ done: done })
// after undoing a todo
this.setState({ done: done-- })
And if you need any more help, just show me the full code.