Coding exercise: build a Todo application in React.
Model answer
Keep the list in state, add with a form, toggle and delete by id. Use a stable id as the key, never the array index, and never change the state array directly.
function Todos() {
const [items, setItems] = useState([]);
const [text, setText] = useState('');
const add = (e) => {
e.preventDefault();
if (!text.trim()) return;
setItems([...items, { id: crypto.randomUUID(), text: text.trim(), done: false }]);
setText('');
};
const toggle = (id) => setItems(items.map((t) => (t.id === id ? { ...t, done: !t.done } : t)));
const remove = (id) => setItems(items.filter((t) => t.id !== id));
return (
<form onSubmit={add}>
<input value={text} onChange={(e) => setText(e.target.value)} placeholder="New task" />
<button>Add</button>
<ul>{items.map((t) => (
<li key={t.id}>
<label><input type="checkbox" checked={t.done} onChange={() => toggle(t.id)} />
<span style={{ textDecoration: t.done ? 'line-through' : 'none' }}>{t.text}</span></label>
<button type="button" onClick={() => remove(t.id)}>Delete</button>
</li>))}</ul>
</form>
);
}Extras that impress: save to localStorage, an empty-state message, and filters for all, active and done.
Tips
- Say out loud that you copy arrays and objects instead of mutating them.
- Mention accessibility: a label for the input and real buttons.
Practise it yourself in the React and Angular code playground.
Learn this topic
React.js Full Course: Beginner to Advanced .
Sign in to add your own answer.
More questions
- Coding exercise: create a search box with debounce in React.
- Coding exercise: fetch API data and display it in a table in React.
- Coding exercise: implement pagination in React.
- Coding exercise: create a login form with validation in React.
- Coding exercise: build a parent-child communication example in React.
- Coding exercise: implement sorting and filtering in React.