Build a shopping list where you can add, tick off, and remove items without mutating state
Build App. It takes an optional initialItems prop, an array of { id, name, bought } objects, and shows them as a list. A form has a text input labelled Item and an Add button. Submitting it, with the button or Enter, adds the trimmed name to the end of the list as not bought and clears the input. Blank names are ignored.
Each item is a list item with a checkbox labelled with the item's name, ticked when it's bought, and a button named Remove <name>, like Remove Milk. Under the list, a paragraph says how many items are bought, like 1 of 3 bought.
Never change initialItems, or any array or object already in state: make new ones.
export default function App({ initialItems = [] }) {
return (
<div>
<form>
<label>
Item <input />
</label>
<button>Add</button>
</form>
<ul>
{initialItems.map((item) => (
<li key={item.id}>{item.name}</li>
))}
</ul>
<p>0 of {initialItems.length} bought</p>
</div>
);
}
- shows the initial items and how many are bought
- adds a trimmed item to the end and clears the input
- Enter adds an item, and blank names are ignored
- ticks an item off and back on
- removes an item
- a new item after a removal gets its own id
- never changes initialItems
The answer
Write it yourself first. Then compare it with a reference solution and the checks it passes.
Checking your sign-in…