react-shopping-cart-kit
v1.0.2
Published
A modern, lightweight, and customizable React shopping cart library with hooks, context API, and beautiful UI components. Perfect for e-commerce websites, marketplaces, and headless commerce apps. Features multi-currency support, dynamic shipping methods,
Maintainers
Keywords
Readme
React Shopping Cart Kit 🛒
A modern, lightweight React shopping cart library with beautiful UI components. Perfect for e-commerce websites and marketplaces.
Features
- Multi-Currency Support - Dynamic currency switching with real-time conversion
- Shipping Methods - Configurable shipping options with costs
- Discount Codes - Percentage or fixed amount discounts
- Internationalization - English and Arabic with RTL support
- TypeScript - Fully typed with generic product types
- Pre-built Components - Beautiful, customizable UI components
- State Management - Built with Zustand for optimal performance
- LocalStorage Persistence - Cart saves automatically
Installation
npm install react-shopping-cart-kit
# or
yarn add react-shopping-cart-kitRequirements
- React 18.0.0+
- React DOM 18.0.0+
- TypeScript 5.0+ (optional but recommended)
Quick Start
1. Import Styles
// main.tsx or App.tsx
import 'react-shopping-cart-kit/styles';2. Wrap Your App with CartProvider
import { CartProvider } from 'react-shopping-cart-kit';
const cartConfig = {
taxRate: 0.08, // 8% tax rate
currency: 'USD', // Default currency
availableCurrencies: [ // Multi-currency support
{ code: 'USD', symbol: '$', name: 'US Dollar', conversionRate: 1.0 },
{ code: 'EUR', symbol: '€', name: 'Euro', conversionRate: 0.92 },
],
shippingMethods: [ // Shipping options
{ id: 'standard', name: 'Standard Shipping', cost: 0, estimatedDays: '5-7 days' },
{ id: 'express', name: 'Express Shipping', cost: 15, estimatedDays: '2-3 days' },
],
discountCodes: [ // Discount codes
{ code: 'SAVE10', amount: 10, type: 'percentage' },
],
showTax: true,
showDiscount: true,
showShipping: true,
};
function App() {
return (
<CartProvider config={cartConfig} language="en">
<YourApp />
</CartProvider>
);
}3. Use the Hook in Your Components
import { useShoppingCart } from 'react-shopping-cart-kit';
function ProductCard({ product }) {
const { addItem, formatCurrency } = useShoppingCart();
return (
<div>
<h3>{product.name}</h3>
<p>{formatCurrency(product.price)}</p>
<button onClick={() => addItem(product)}>
Add to Cart
</button>
</div>
);
}4. Add Pre-built Components (Optional)
import { CartButton, CartDrawer, CartSummary, CurrencySelector } from 'react-shopping-cart-kit';
function Header({ onLanguageChange, currentLanguage }: { onLanguageChange: (lang: string) => void; currentLanguage: string }) {
return (
<header className="header">
<div className="header-brand">
<h1>Razan's Premium Commerce</h1>
</div>
<div className="header-actions">
<button
onClick={() => onLanguageChange(currentLanguage === 'en' ? 'ar' : 'en')}
className="lang-switcher"
>
{currentLanguage === 'en' ? 'العربية' : 'English'}
</button>
<CartButton showBadge badgePosition="top-right" />
</div>
</header>
);
}
function App() {
const [language, setLanguage] = useState('ar');
const cartConfig = {
taxRate: 0.08,
currency: 'USD',
availableCurrencies: [
{ code: 'USD', symbol: '$', name: 'US Dollar', conversionRate: 1.0 },
{ code: 'EUR', symbol: '€', name: 'Euro', conversionRate: 0.92 },
],
shippingMethods: [
{ id: 'standard', name: 'Standard Shipping', cost: 0, estimatedDays: '5-7 days' },
{ id: 'express', name: 'Express Shipping', cost: 15, estimatedDays: '2-3 days' },
],
discountCodes: [
{ code: 'SAVE10', amount: 10, type: 'percentage' },
],
showTax: true,
showDiscount: true,
showShipping: true,
};
return (
<CartProvider config={cartConfig} language={language}>
<div className="app">
<Header onLanguageChange={setLanguage} currentLanguage={language} />
<CartDrawer
position="center"
closeOnOverlayClick={true}
showCheckoutButton={true}
checkoutButtonText="Proceed to Checkout"
onCheckout={() => alert('Checkout clicked!')}
/>
<main className="main-content">
<ProductList />
<div className="summary-section">
<CartSummary showTax={true} showDiscount={true} />
</div>
</main>
</div>
</CartProvider>
);
}Components
CartProvider
Wraps your app to provide cart context.
<CartProvider config={cartConfig} language="en">
<YourApp />
</CartProvider>Props:
config- Configuration object (see Configuration section)language- Language code:'en'or'ar'(default:'en')
CartButton
Shopping cart icon with badge showing item count.
<CartButton showBadge badgePosition="top-right" />Props:
showBadge- Show item count badge (default:true)badgePosition-'top-right'or'top-left'(default:'top-right')className- Additional CSS classesonClick- Click handler
CartDrawer
Side cart with smooth animation. Can be positioned as side drawer or centered popup.
<CartDrawer position="right" showCheckoutButton onCheckout={() => {}} />Props:
position-'right','left', or'center'(default:'right')showCheckoutButton- Show checkout button (default:true)onCheckout- Checkout handler functionclassName- Additional CSS classes
CartSummary
Displays subtotal, discount, taxes, shipping, and total.
<CartSummary showTax={true} showDiscount={true} showShipping={true} />Props:
showTax- Show tax line (default:true)showDiscount- Show discount line (default:true)showShipping- Show shipping selection (default:true)
CurrencySelector
Currency dropdown for switching between currencies.
<CurrencySelector compact />Props:
compact- Use compact dropdown style (default:false)showCurrencyName- Show full currency name (default:true)
CartItems
Renders all items in the cart.
<CartItems emptyMessage="Your cart is empty" />Props:
emptyMessage- Message when cart is empty (default:'Your cart is empty')showRemoveButton- Show remove button on items (default:true)
CartItem
Individual cart item component.
<CartItem item={product} showRemoveButton={true} />Props:
item- Cart item data (required)showRemoveButton- Show remove button (default:true)
CheckoutButton
Primary checkout button with loading state.
<CheckoutButton loading={false} onClick={() => {}}>
Checkout
</CheckoutButton>Props:
loading- Show loading state (default:false)disabled- Disable button (default:false)onClick- Click handler
useShoppingCart Hook
The main hook for accessing cart state and actions.
const {
// State
items,
subtotal,
tax,
shippingCost,
discountAmount,
total,
selectedCurrency,
// Actions
addItem,
removeItem,
updateItemQuantity,
clearCart,
applyDiscount,
removeDiscount,
setSelectedShippingMethod,
setSelectedCurrency,
formatCurrency,
} = useShoppingCart();State Properties
items- Array of cart itemssubtotal- Subtotal in selected currencytax- Tax amount in selected currencyshippingCost- Shipping cost in selected currencydiscountAmount- Discount amount in selected currencytotal- Total amount in selected currencyselectedCurrency- Currently selected currency code
Action Methods
addItem(product)- Add product to cartremoveItem(id)- Remove item from cartupdateItemQuantity(id, quantity)- Update item quantityclearCart()- Clear all items from cartapplyDiscount(code)- Apply discount by coderemoveDiscount()- Remove applied discountsetSelectedShippingMethod(methodId)- Select shipping methodsetSelectedCurrency(currencyCode)- Switch currencyformatCurrency(amount)- Format amount with current currency
Configuration
CartConfig Object
{
// Basic Settings
taxRate: 0.08, // Tax rate as decimal (0.08 = 8%)
currency: 'USD', // Default currency code
storageKey: 'react-shopping-cart', // localStorage key
persistToLocalStorage: true, // Enable localStorage persistence
// Currency Configuration
availableCurrencies: [...], // Array of Currency objects
showCurrencySelector: true, // Show currency selector
decimalPlaces: 2, // Number of decimal places
// Shipping Configuration
shippingMethods: [...], // Array of ShippingMethod objects
showShipping: true, // Show shipping section
// Discount Configuration
discountCodes: [...], // Array of DiscountCode objects
showDiscount: true, // Show discount input
// Display Options
showTax: true, // Show tax line
theme: 'light', // 'light', 'dark', or 'auto'
}Currency Object
{
code: 'USD', // Currency code
symbol: '$', // Currency symbol
name: 'US Dollar', // Display name
conversionRate: 1.0, // Conversion rate from base currency
}ShippingMethod Object
{
id: 'standard', // Unique ID
name: 'Standard Shipping', // Display name
description: '5-7 business days', // Description
cost: 0, // Cost in base currency
estimatedDays: '5-7 days', // Estimated delivery
isDefault: false, // Is default option
}DiscountCode Object
{
code: 'SAVE10', // Discount code
amount: 10, // Discount amount
type: 'percentage', // 'percentage' or 'fixed'
expiryDate?: '2024-12-31', // Optional expiry date
usageLimit?: 100, // Optional usage limit
}Multi-Currency Support
All calculations (subtotal, tax, discount, shipping, total) are performed in the selected currency.
Example:
// Base: USD, User selects EUR (rate: 0.92)
// $100 product → €92
// Subtotal: €92 (converted)
// Tax (8%): €7.36 (calculated on converted amount)
// Total: €99.36 (all in EUR)Internationalization
Built-in support for English and Arabic with automatic RTL layout for Arabic.
Set language:
<CartProvider config={cartConfig} language="ar">
<YourApp />
</CartProvider>Available languages:
en- English (default)ar- Arabic (with RTL support)
TypeScript Support
Fully typed with TypeScript. Extend the base product type for type safety:
import { BaseProduct, useShoppingCart } from 'react-shopping-cart-kit';
interface MyProduct extends BaseProduct {
sku: string;
category: string;
}
function ProductPage() {
const { addItem, items } = useShoppingCart<MyProduct>();
const handleAdd = () => {
addItem({
id: '1',
name: 'Product',
price: 29.99,
sku: 'SKU-001',
category: 'Electronics',
});
};
}Customization
CSS Variables
Override CSS variables to customize the appearance:
:root {
--rsc-primary-color: #3b82f6;
--rsc-primary-hover: #2563eb;
--rsc-accent-color: #10b981;
--rsc-danger-color: #ef4444;
}Custom Styling
<CartButton
className="bg-purple-600 hover:bg-purple-700 text-white"
badgeClassName="bg-pink-500 text-white"
/>License
MIT © Razan Aboushi
Support
- 📧 Email: [email protected]
- 🐛 GitHub: https://github.com/razan-aboushi/react-shopping-cart
- 💼 LinkedIn: https://www.linkedin.com/in/razan-aboushi/
- 📦 NPM: https://www.npmjs.com/package/react-shopping-cart-kit
