1

I have created a todo app and I am trying to filter todos in 3 different conditions all, completed, incompleted. As default I want to show all the items and then filter them. I know that I can use filter as follow for example:

array.filter(t => t.completed) or array.filter(t => !t.completed)

but I dont know how to render all of them and then render the filtered items only. The code is as follow:

render() {
let notes = this.state.notes.filter(n => n.completed).map((todo, 
index) => {
  return (
    <Todo 
      key={index} 
      note={todo} 
      deleteTodo={() => this.deleteTodo(index)} 
      handleClick={() => this.handleClick(index)}/>
  );
});
const allNotes = this.state.notes.length
let completedNotes = this.state.notes.filter(n => n.completed).length
let incompletedNotes = this.state.notes.filter(n => 
!n.completed).length
return (<div>{notes}</div>);
4
  • 1
    That depends on how you render them currently? Can you share your code and what doesn't work? Commented Aug 13, 2018 at 13:07
  • Just edited the post with the current code. Commented Aug 13, 2018 at 13:12
  • How you determine which items should be shown (all, completed, incomplete) ? Commented Aug 13, 2018 at 13:17
  • This is the point where I am stack now. I have 3 buttons (all, completed, incomplete) which are showing the number of each (all, completed, incomplete) but I dont know how to make them active. As for the filter that I am using with the map is not working properly. Commented Aug 13, 2018 at 13:21

2 Answers 2

3

What you are describing can be accomplished many ways, but a straightforward answer would be to use state (or props if the filter is controlled via a parent):

getFilteredNotes() {
  switch (this.state.noteFilter) {
    case 'completed':
      return this.state.notes.filter(n => n.completed);
    case 'incomplete'
      return this.state.notes.filter(n => !n.completed);
    case 'all':
    default:
      return this.state.notes;
}

render() {
  return this.getFilteredNotes().map(n => (
    <Todo note={n}/>
  ));
}
Sign up to request clarification or add additional context in comments.

Comments

1

Just render the filtered array with map;

render() {
  return (
    <div>
       {this.state.todos.filter(t => t.completed).map(t => (
         <TodoItem>{t.text}</TodoItem>
        }
    </div>
  )
}

Comments

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.