Shopping Cart Component
TheFirstSteps component demonstrates how to build a shopping cart that manages multiple items, each with its own counter. This example shows how to work with arrays of data and render dynamic lists of components in React.
Complete Implementation
Understanding the Code
ItemInCart Interface
TheItemInCart interface defines the structure for each product in the cart:
Using TypeScript interfaces ensures type safety when working with cart items throughout your application.
Cart Data Structure
The shopping cart is initialized with an array of items:- Hardcoded for demo purposes (as shown)
- Fetched from an API
- Loaded from local storage
- Managed by a state management solution
Rendering the List
The component uses themap() method to render an ItemCounter for each item:
- Destructuring:
{ productName, quantity }extracts properties directly from each item - Key prop:
key={productName}helps React efficiently track and update each component - Props passing: Each
ItemCounterreceivesnameandquantityas props
The
key prop is essential when rendering lists in React. It should be a unique identifier for each item. In production, use a unique ID rather than the product name.Component Structure
ItemCounter maintains its own state independently, allowing users to adjust quantities for individual products.
Use Cases
- E-commerce shopping carts
- Inventory management systems
- Order forms with multiple items
- Product comparison lists
- Wish lists with quantity tracking
Next Steps
- Learn about the ItemCounter component used in this example
- Explore state management with React hooks
- Add features like item removal, total calculation, or persistence