On part 1, I went through how to set up a todo app using react, creating components so that when we add a new item to the list, it adds up in the list. Now I am going to cover how to handle the checkmarks to mark an item as completed, handle the delete button and filter the todos with their status.
In the Todo.js component, I created a constant arrow function ‘deleteHandler’ so that I could modify the state using the filter method. In order to pass down the state for the setTodos from App.js to Todo.js, we had it as a prop in App.js in the TodoList component, then in the TodoList component, we pass it a props for the Todo component. Then add an event listener to the button to use this function ‘deleteHandler’ that will update the state whenever it is clicked, removing the item from the list that matches the id.
Similar to the delete button, I create a constant in Todo.js called ‘completeHandler’. This time I mapped over the todos to collect the items that have the same status and add them to the array. Then add an event listener to the checkmark to use this function and update the classname so that it marks as checked when done using our CSS.
First, create a constant to App.js for the status and set it equal to “all” by default. This is part of the Form component so we have to pass it as a prop in our Form component. In Form.js, create a const called “statusHandler” that will set the status when we select a status. Our select tag needs to call this function.
Now that the state is updated, we need to add a constant that I called [‘filteredTodos’, setFilteredTodos’] in App.js and set it equal to an empty array. Then create another function called ‘filterHandler’ and by using the switch method, filter out the todos and mark them to the correct status. By default, it will set to ‘all’.
Next, by using useEffect() hook, we run the function every time the state changes. To implement useEffect(), add it to the imported hooks on line 1, and below the state constants, write a useEffect arrow function that will call the filerHandler function as the first argument, and update the state and the todos every time we filter the items.
Last step, we need to update the UI. To do so, we need to update TodoList.js which is the one component responsible to render the list based on the state. Pass it as a props in the App.js and import it in the TodoList component so you can map it.
Last but not least if you want this app to be fully functional, is to save it on the local storage so that when you refresh the page it keeps in memory your todos.
In App.js, write a constant called ‘saveLocalTodos’ using an arrow function to save the items on the local storage. Then write a 2nd constant called ‘getLocalTodos’ to check if there are items on the local storage and parse these items if any.
Tip: In case you encounter an error, you might need to clear the datas in the local storage. Go in your developer, application, storage and clear site data.