Todo List
In this exercise, you are tasked with creating a simple Todo List component that allows users to add new items to the list and delete items once they are completed. The Todo List should have the following features:
An input field for adding new todo items
A button to submit the new todo item
Display the list of todo items
A delete button next to each todo item to remove it from the list
useState
hook to manage the todo list stateSolution Walkthrough for Todo List
Spoiler Alert!
Don't read this unless you've already solved the problem.
List Rendering:
map
function to iterate over the todos
array and render a list item for each todo.Event Handling:
onClick
and onChange
, which allow you to execute functions when specific events occur. In this exercise, we'll use the onClick
event handler to handle the submission and deletion of todo items, and the onChange
event handler to update the input field value.todos
and inputValue
:useState
hook. todos
is an array that stores the list of todo items, and inputValue
stores the current value of the input field.const [todos, setTodos] = useState([]);
const [inputValue, setInputValue] = useState('');
handleInputChange
, handleSubmit
, and handleDelete
functions:handleInputChange
updates the inputValue
state variable whenever the input field value changes.function handleInputChange(event) {
setInputValue(event.target.value);
}
handleSubmit
adds a new todo item to the todos
array when the "Add Todo" button is clicked. Before adding the item, it checks if the trimmed input value is not empty to prevent adding empty or whitespace-only items.function handleSubmit() {
if (inputValue.trim()) {
setTodos([...todos, inputValue.trim()]);
setInputValue('');
}
}
handleDelete
removes a todo item from the todos
array based on its index.function handleDelete(index) {
setTodos(todos.filter((_, i) => i !== index));
}
handleInputChange
, handleSubmit
, and handleDelete
functions to the corresponding event handlers:handleInputChange
function to the input field's onChange
event handler and set its value to the current inputValue
state.<input type="text" value={inputValue} onChange={handleInputChange} />
handleSubmit
function to the "Add Todo" button's onClick
event handler.<button onClick={handleSubmit}>Add Todo</button>
Display the list of todo items:
map
function to iterate over the todos
array, rendering a list item for each todo. We also attach a "Delete" button to each list item with the handleDelete
function, passing the item's index.<ul>
{todos.map((todo, index) => (
<li key={index}>
{todo}
<button onClick={() => handleDelete(index)}>Delete</button>
</li>
))}
</ul>
useState
hook manages the todo list state, making it easy to update and maintain.