Coding exercise: build a Todo application in React.

React practical coding · Freshers

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

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