Todo List
MediumReact Components20 min5 tests
Build a todo list where users type a task, click Add to append it (trimmed) with its own Delete button, and clearing the input. Empty or whitespace-only input adds nothing; Delete removes that specific item.
Create a small Todo List component.
The UI has:
- A text input with the placeholder
Add a todo. - An
Addbutton.
Behavior:
- Clicking Add takes the current input value, trims surrounding whitespace, and appends it as a new list item. Each item renders its own Delete button.
- After a successful add, the input is cleared.
- If the input is empty or contains only whitespace, nothing is added (and the input may stay as-is or clear — but no item appears).
- Clicking an item's Delete button removes just that item from the list. Other items keep their order.
Items are rendered as an accessible list (<ul>/<li>). Because duplicate text is allowed, do not key items by their text alone — give each todo a stable unique id.
Requirements
- Render a text input with placeholder "Add a todo" and an "Add" button.
- Clicking Add appends the trimmed input value as a new list item.
- After adding, clear the input.
- Empty or whitespace-only input must not add any item.
- Each todo item has its own accessible "Delete" button (use an aria-label that identifies the item, e.g. "Delete <text>").
- Clicking a todo's Delete button removes only that item.
- Use a stable unique id per todo (duplicates are allowed), not the text, as the React key.
Hints (4)
- Track todos in state as an array of objects like { id, text }, and use a counter ref or incrementing id so duplicate text still gets unique keys.
- On Add, compute const trimmed = input.trim(); return early if (!trimmed) so empty/whitespace input adds nothing.
- Give each Delete button aria-label={
Delete ${todo.text}} so tests can query it accessibly with getByRole('button', { name: /delete buy milk/i }). - Delete with setTodos(todos.filter(t => t.id !== id)) so only the matching item is removed.
Topics
- React
- React Components
Asked at
MakeMyTrip · Rapido · Freshworks · Amazon · Atlassian · Zomato
