Item Counter Component
TheItemCounter component is a reusable counter that manages item quantities. It demonstrates fundamental React concepts including props, state management with useState, event handlers, and conditional styling.
Complete Implementation
Props Interface
The component accepts two props:The
quantity prop is optional (indicated by ?), which means it can be omitted when using the component. However, in the current implementation, it’s not being used to initialize the state.State Management
useState Hook
The component uses theuseState hook to track the current count:
count: The current state valuesetCount: Function to update the stateNumber: Passing the Number constructor as initial value (results in NaN initially)
Event Handlers
Increment Handler
ThehandleAdd function increases the count by 1:
Decrement Handler
ThehandleSub function decreases the count, with validation:
The early return pattern (
if (count === 0) return;) is a common way to add guard clauses and prevent invalid state updates.Conditional Styling
The component applies dynamic styling based on the count:CSS Modules
The component uses CSS Modules for scoped styling:CSS Modules automatically scope class names to prevent conflicts. The
styles['item-row'] syntax accesses the scoped class name.Component Layout
The component renders a horizontal layout:- Product name (fixed width of 200px)
- Increment button
- Current count display
- Decrement button
Key Features
✓ Reusable: Can be used for any product or item✓ State Management: Tracks quantity independently
✓ Validation: Prevents negative quantities
✓ Visual Feedback: Color changes when count is zero
✓ Type Safe: TypeScript interface ensures correct prop usage
Usage Example
Potential Improvements
Common Use Cases
- Shopping cart item quantities
- Inventory management
- Order forms
- Ticket selection
- Guest count selectors
- Product comparison quantities
Related Examples
- Shopping Cart - See how multiple ItemCounters work together