Skip to main content

Simple Todo List

Build a basic todo list where the user can type a task and add it to a list. The component must display an input field for the task text, an "Add" button, and a list of all added tasks. The component should ignore empty or whitespace-only inputs, and after adding a valid task, it must clear the input field

Input actions:
1. Type: "Study React" β†’ click "Add"
2. Type: "Practice English" β†’ click "Add"
3. Type: " " β†’ click "Add"

Output:
- Todo list shows:
- Study React
- Practice English
- The third action adds nothing.
import React, { useState, ChangeEvent, FormEvent } from 'react';

type TodoListProps = {
initialItems?: string[];
};

export default function TodoList({ initialItems = [] }: TodoListProps) {
const [items, setItems] = useState<string[]>(initialItems);
const [inputValue, setInputValue] = useState('');

const handleChange = (event: ChangeEvent<HTMLInputElement>) => {
setInputValue(event.target.value);
};

const handleSubmit = (event: FormEvent) => {
event.preventDefault();

const trimmed = inputValue.trim();
if (!trimmed) return;

setItems((prev) => [...prev, trimmed]);
setInputValue('');
};

return (
<div>
<h2>Todo List</h2>

<form onSubmit={handleSubmit}>
<input
type="text"
placeholder="Add a new task..."
value={inputValue}
onChange={handleChange}
/>
<button type="submit">Add</button>
</form>

<ul>
{items.map((task, index) => (
<li key={index}>{task}</li>
))}
</ul>
</div>
);
}