ToDoList Component

Learn how to further break down a React component into smaller parts.

Add ToDoList

Because we’re working with function-based components, we can also pass arguments and parameters to React components, like we can with functions in JavaScript. This ToDoList component takes props (properties) and provides data to these props as an argument when we call the ToDoList component in the input.js file. The component receives the argument as a props object. We create a list of tasks that appear in CSS-grid format to show our output.

List of tasks

We pass an item property to this component that has an array of all task objects with toDo properties. These properties have the value input task and unique id created by nanoid. We then map over the item tasks to return them.

<ul className="appToDoHolder">
  {(props.item).map((item) => {
  return ()
</ul>

Add the unique ids

Mapping over the item array returns the object with the id property, which we pass as key props into the div.

Note: Passing the unique id only with the key prop is mandatory.

return (
  <ul className="appToDoHolder">
  {(props.item).map((item) => {
    return (
     <div className="appToDo" key={item.id}> </div>
    )
  })}     
);

Add the Todo task

We also get tasks as a toDo property that passes into the <li></li> element.

return (
  <ul className="appToDoHolder">
  {(props.item).map((item) => {
    return (
     <div className="appToDo" key={item.id}>
       <li>{item.toDo}</li>           
     </div>
    )   
  })}  
);

Add the onDelete function

The onDelete attribute handles the onDeleteHandler method, which deletes the task. We’ll send item.id as an argument to the onDeleteHandler to delete only the selected item. Because we’re calling onDeleteHandler on every click in this component, we pass item.id here.

return (
  <ul className="appToDoHolder">
  {(props.item).map((item) => {
    return (
     <div className="appToDo" key={item.id}>
       <li>{item.toDo}</li> 
         <button 
         className="appDelete" 
         title="delete"
         onClick={() => 
        props.onDelete(item.id)}> Delete </button>          
     </div>
    )   
  })}  
);

Combining all code snippets above produces the following snippet:

Get hands-on with 1200+ tech skills courses.