Beginner’s Guide to React JS: Part 40 – Building a Todo App with Delete Functionality [2023] #infysky #code

Posted by

React JS Tutorial For Beginners: Part-40 Todo App Part-15 Delete Functionality

React JS Tutorial For Beginners: Part-40 Todo App Part-15 Delete Functionality

Welcome to part 40 of our React JS tutorial series. In this tutorial, we will be adding delete functionality to our todo app. This will allow users to remove items from their todo list with ease.

First, let’s create a new component called DeleteButton. This component will be responsible for rendering a button that will allow users to delete a todo item.

“`javascript
import React from ‘react’;

function DeleteButton({onDelete}) {
return (

);
}

export default DeleteButton;
“`

Next, we need to update our TodoItem component to render the DeleteButton component and pass the delete function as a prop.

“`javascript
import React from ‘react’;
import DeleteButton from ‘./DeleteButton’;

function TodoItem({todo, onDelete}) {
return (

{todo.text}

onDelete(todo.id)} />

);
}

export default TodoItem;
“`

Finally, we need to update our TodoList component to handle the delete functionality. We will use the filter method to remove the item from the todo list when the delete button is clicked.

“`javascript
import React, { useState } from ‘react’;
import TodoItem from ‘./TodoItem’;

function TodoList() {
const [todos, setTodos] = useState([
{ id: 1, text: ‘Finish React tutorial’ },
{ id: 2, text: ‘Start new project’ },
{ id: 3, text: ‘Go for a run’ }
]);

const handleDelete = (id) => {
setTodos(todos.filter(todo => todo.id !== id));
}

return (

{todos.map(todo => (

))}

);
}

export default TodoList;
“`

That’s it! Now our todo app has delete functionality, allowing users to easily remove items from their todo list. Stay tuned for the next part of our tutorial series where we will be adding more features to our todo app.