2024-07-08
Creating a Todo List App in React
This component maintains a list of todos (todos
) using the useState
hook. It allows adding new todos through an input field and a button (handleAddTodo
function). Each todo item has a delete button (handleDeleteTodo
function) to remove it from the list.
import React, { useState } from 'react';
function TodoList() {
const [todos, setTodos] = useState([]);
const [inputValue, setInputValue] = useState('');
const handleInputChange = (e) => {
setInputValue(e.target.value);
};
const handleAddTodo = () => {
if (inputValue.trim() !== '') {
setTodos([...todos, { id: todos.length + 1, text: inputValue }]);
setInputValue('');
}
};
const handleDeleteTodo = (id) => {
setTodos(todos.filter((todo) => todo.id !== id));
};
return (
<div>
<h1>Todo List</h1>
<div>
<input
type="text"
value={inputValue}
onChange={handleInputChange}
placeholder="Enter a todo..."
/>
<button onClick={handleAddTodo}>Add</button>
</div>
<ul>
{todos.map((todo) => (
<li key={todo.id}>
{todo.text}
<button onClick={() => handleDeleteTodo(todo.id)}>Delete</button>
</li>
))}
</ul>
</div>
);
}
export default TodoList;