Deviopath › React

Cart with Context and Reducer

Hard · Context

Share a shopping cart between several components. Goal: practise createContext + useReducer (actions "add", "remove", "clear").

App renders the provider around three components that read the cart from context:

- CartBadge inside a <header>: <span className="badge">Cart (3)</span> with the total number of units.

- ProductList: for each product a <div className="product"> with <h3> name, <p> price and an "Add to cart" button.

- CartPanel: a <ul> with one <li> per product in the cart, containing <span>Keyboard x2</span> and a "Remove" button that removes ONE unit (the line disappears at 0). Lines keep the order in which products were first added. When the cart is empty show <p className="empty">Your cart is empty</p> instead of the list. Always show <p className="total">Total: 120</p> and a "Clear cart" button.

Next: Habit Tracker That Survives a Reload