I am currently working on a todo list app, and i am trying to implement a function where users can filter tasks based on their completion status (all, completed, or uncompleted). I am trying to use the javascript filter function.'
I have tried using a duplicate array, therefore retaining the original values, and manipulating the duplicate array. However, I could not get the original array to update as the list increases, so i decided to scrap that.
There is a lot of code in my project but i will only copy the ones relevant to the question.
const Body = () => {
let tasks = [
{
task: 'Walk the dog',
completed: false,
id: Math.round(Math.random() * 100000),
},
{
task: 'Learn ReactJS',
completed: false,
id: Math.round(Math.random() * 100000),
},
];
const [task, setTask] = useState(tasks);
const addTask = () => {
let input = document.getElementById('task-field');
let randomID = Math.round(Math.random() * 100000);
if (input != null) {
setTask([...task, { task: input.value, completed: false, id: randomID }]);
}
};
return (
<div className='body'>
<Header></Header>
<Input setMethod={set} inputMethod={addTask}></Input>
<Tasks tasks={task} display={display} removeMethod={complete}></Tasks>
</div>
);
};
export default Body;
const Tasks=({tasks, display, removeMethod,})=> {
const [task,setTask] = useState(tasks)
const [display,setDIsplay] = useState(tasks)
const filterFunction=(event)=> {
let filtered;
const target = event.target;
switch(target.innerHTML) {
case('All'):
filtered = task
break;
case('Active'):
filtered = task.filter(()=> {
return !task.completed
})
break;
case('Completed'):
filtered = task.filter(()=> {
return task.completed
})
setDisplay(filtered)
}
}
return(
<div className="tasks">
{display.map(el=> {
return (
<TaskComponent task={el} removeMethod = {removeMethod} key = {el.id}></TaskComponent>
)
})}
<Footer method = {filterFunction} ></Footer>
</div>
)
}
export default Tasks;
so the question is, how do i implement this feauture in ReactJS?
for reference, i am linking a fellow coder's take on the same project : https://nasratt.github.io/frontendMentorSolutions/projects/todoList/
thanks in advance for the help.