Import ToDoList Component

Get to know how to pass the props in a function.

The ToDoList component

Let’s now import the ToDoList component and set the item and onDelete properties. The item property contains an array of tasks that are mapped over to display a list of tasks.

The onDeleteHandler method handles the onDelete function, which deletes the tasks based on their unique ids. We return the ToDoList component after importing the component.

<form> ... </form>

<ToDoList/>

Passing the list

The value of the toDoList state used for the useState hook is now stored in this item prop.

<ToDoList
  item={toDoList}
/>

Then we write the onDeleteHandler function, which takes the itemID. That’s the element’s unique id. We then use the filter method to populate setToDoList with all elements except for that with the given id.

Note: Read more about the filter function from the following Educative Answer post onfilter.

Each time we click the “delete” button, the itemID parameter takes the unique id of that task as the value.

const onDeleteHandler = (itemID) => {
  setToDoList((oldValues) =>
     oldValues.filter((item) => {
       return item.id !== itemID;
     })
  );
};

This function should now pass to the ToDoList component.

<ToDoList
  item={toDoList}
  onDelete={onDeleteHandler}
/>

We should now get the following snippet after combining all the code above:

Get hands-on with 1400+ tech skills courses.