Now that we have our Todo App scaffolding, we want to place dummy todo items on our page. We’re doing this so we have everything set in place when we get started on adding functionality to add todo items. For now, we’re going to use dummy data to see what our todo items will look like
We want to use React’s useState hook to create an array of todo items.
...
const Todo = () => {
const [todoItems, updateTodoItems] = useState([{ title: 'Get groceries'}, {title: 'Fill up on gas' }]);
...
Next we want to run todoItems.map
in our render function to display our dummy todo items.
<IonGrid>
{todoItems.map((todoItem, index) => (
<IonRow>
<IonCol size="12">
<IonItem>
<IonGrid>
<IonRow>
<IonCol size-sm="8" size-md="10" size-lg="11" class="ion-align-self-center">
<IonText>{todoItem.title}</IonText>
</IonCol>
<IonCol size-sm="4" size-md="2" size-lg="1" class="ion-text-center">
<IonButton>Delete</IonButton>
</IonCol>
</IonRow>
</IonGrid>
</IonItem>
</IonCol>
</IonRow>
))}
</IonGrid>
We want to have a delete button for when we’re finished with a todo item. Lets add that alongside our text.
{todoItems.map((todoItem, index) => (
<IonGrid>
<IonRow>
<IonCol size="8">
<IonText>{todoItem.title}</IonText>
<IonText>{todoItem.description}</IonText>
</IonCol>
<IonCol size="4">
<IonButton onClick={() => deleteTodo(index)}>Delete</IonButton>
</IonCol>
</IonRow>
</IonGrid>
))}
And of course, we would need to create the deleteTodo
function
First thing we want to do is duplicate the todoItems variable we use for our state. Its very important that you use Object.create or the spread operator here.
function deleteTodo(index) {
const todoItemsClone = Object.create(todoItems, []);
}
The next thing we want to do is remove the chosen item from our todoItemsClone variable. The process of removing the item from the array is done using the splice method available to Arrays in Javascript.
function deleteTodo(index) {
const todoItemsClone = Object.create(todoItems, []);
todoItemsClone.splice(index,1);
}
Finally we want to update our state variable todoItems to show that we’ve deleted our chosen todo item.
function deleteTodo(index) {
const todoItemsClone = Object.create(todoItems, []);
todoItemsClone.splice(index,1);
updateTodoItems(todoItemsClone);
}