Package Exports
- shopping-cart-react
- shopping-cart-react/dist/index.js
- shopping-cart-react/dist/shopping-cart-react.esm.js
This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (shopping-cart-react) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.
Readme
shopping-cart-react
A tiny React library for managing a shopping cart with tons of features, built with TypeScript.
Why?
- 1 dependency
- 🔥 Persistent carts with local storage
- 🥞 Works with Next, React, more...
- 🛠 Built with TypeScript
- ✅ Fully tested
- 📦 Works out of the box
Quick Start
import 'react-app-polyfill/ie11';
import * as React from 'react';
import * as ReactDOM from 'react-dom';
import { useCart } from '../src';
import { formatCurrencyString } from '../src/utils';
const App = () => {
const {
addItemToCart,
removeItemFromCart,
clearCart,
cartItems,
formattedTotalPrice,
totalPrice,
cartCount,
isEmpty,
incrementQuantity,
} = useCart();
const addApple = () => addItemToCart({ id: '1', name: 'apple', price: 100 });
const addOrange = () =>
addItemToCart({ id: '2', name: 'orange', price: 200 });
const addBanana = () => addItemToCart({ id: '3', name: 'banana', price: 87 });
return (
<div>
<button onClick={addApple}>Add apple</button>
<button onClick={addOrange}>Add orange</button>
<button onClick={addBanana}>Add banana</button>
<button onClick={() => removeItemFromCart('1')}>Remove apple</button>
<button onClick={clearCart}>Clear Cart</button>
<button onClick={() => incrementQuantity('3')}>Increment banana</button>
<div>
<h2>Cart Items</h2>
<ul>
{cartItems.map(item => (
<li key={item.id}>
{item.quantity} x {item.name} -
{formatCurrencyString({ currency: 'USD', value: item.price })}
</li>
))}
</ul>
<h3>Total Price: ${totalPrice}</h3>
<h3>Formatted Total Price: {formattedTotalPrice}</h3>
<h3>Cart Count: {cartCount}</h3>
<h3>Is Cart Empty: {isEmpty ? 'Yes' : 'No'}</h3>
</div>
</div>
);
};
ReactDOM.render(<App />, document.getElementById('root'));
Install
npm install shopping-cart-react
or
yarn add shopping-cart-react
States and Actions
Prop | Type | Description |
---|---|---|
cartItems |
State | An array of products in the cart, each with attributes like name , id , price , etc. |
cartCount |
State | Total quantity of items in the cart. |
isEmpty |
State | Boolean value indicating if the cart is empty. |
totalPrice |
State | Total price of all items in the cart. |
formattedTotalPrice |
State | Formatted total price of items in the cart, according to the selected currency. |
currency |
State | The currency used for displaying the cart total. Default is 'USD'. |
setCurrency |
Action | Function to set the cart's currency. |
addItemToCart |
Action | Function to add a new item to the cart. |
updateQuantity |
Action | Function to update the quantity of a specific item in the cart by product ID and quantity. |
incrementQuantity |
Action | Function to increase the quantity of a specific item in the cart by one. |
decrementQuantity |
Action | Function to decrease the quantity of a specific item in the cart by one. |
removeItemFromCart |
Action | Function to remove a specific item from the cart by product ID. |
clearCart |
Action | Function to clear all items from the cart, resetting the cart state. |
updateCartMetrics |
Action | Function to update cart metrics like total price and item count based on current cart state automatically called after a action that changes cart metrics. |
useCart
The useCart
hook exposes all the above States and Actions.
cartItems
Type: State
Description: An array of products currently in the cart. Each product object includes attributes such as name
, id
, price
, etc.
Usage
import { useCart } from 'shopping-cart-react';
const CartItemsExample = () => {
const { cartItems } = useCart();
return (
<div>
<h2>Cart Items</h2>
<ul>
{cartItems.map(item => (
<li key={item.id}>
{item.name} - ${item.price / 100}
</li>
))}
</ul>
</div>
);
};
cartCount
Type: State
Description: Total quantity of all items in the cart.
Usage
import { useCart } from 'shopping-cart-react';
const CartCountExample = () => {
const { cartCount } = useCart();
return (
<div>
<h2>Total Items</h2>
<p>{cartCount}</p>
</div>
);
};
isEmpty
Type: State
Description: A boolean indicating whether the cart is empty.
Usage
import { useCart } from 'shopping-cart-react';
const CartIsEmptyExample = () => {
const { isEmpty } = useCart();
return (
<div>
{isEmpty ? <p>Your cart is empty.</p> : <p>Your cart has items.</p>}
</div>
);
};
totalPrice
Type: State
Description: Total price of all items in the cart in cents (USD).
Usage
import { useCart } from 'shopping-cart-react';
const TotalPriceExample = () => {
const { totalPrice } = useCart();
return (
<div>
<h2>Total Price</h2>
<p>{totalPrice}</p>
</div>
);
};
formattedTotalPrice
Type: State
Description: Formatted total price of items in the cart, adjusted according to the selected currency.
Usage
import { useCart } from 'shopping-cart-react';
const FormattedTotalPriceExample = () => {
const { formattedTotalPrice } = useCart();
return (
<div>
<h2>Formatted Total Price</h2>
<p>${formattedTotalPrice}</p>
</div>
);
};
currency
Type: State
Description: The currency used for displaying the cart total. Default is 'USD'.
Usage
import { useCart } from 'shopping-cart-react';
const CurrencyExample = () => {
const { currency } = useCart();
return (
<div>
<h2>Current Currency</h2>
<p>{currency}</p>
</div>
);
};
setCurrency
Type: Action
Description: Function to set the cart's currency.
Args
- currency (Required): The currency code to set, e.g., 'USD', 'EUR', etc.
Usage
import { useCart } from 'shopping-cart-react';
const SetCurrencyExample = () => {
const { setCurrency } = useCart();
return (
<div>
<button onClick={() => setCurrency('EUR')}>Set Currency to EUR</button>
</div>
);
};
addItemToCart
Type: Action
Description: Function to add a new item to the cart.
Args
- item (Required): type Product
export interface Product {
name: string;
description?: string;
id: string;
price: number;
image?: string;
price_id?: string;
sku_id?: string;
sku?: string;
price_data?: any;
product_data?: any;
quantity?: number;
}
Usage
import { useCart } from 'shopping-cart-react';
const AddItemToCartExample = () => {
const { addItemToCart } = useCart();
const newItem = {
id: 'example-id',
name: 'Sample Item',
price: 2000, // $20.00
};
return (
<div>
<button onClick={() => addItemToCart(newItem)}>Add Sample Item</button>
</div>
);
};
updateQuantity
Type: Action
Description: Function to update the quantity of a specific item in the cart.
Args
- itemId (Required): The id of the item to update.
- quantity (Required): The new quantity for the item.
Usage
import { useCart } from 'shopping-cart-react';
const UpdateQuantityExample = () => {
const { updateQuantity } = useCart();
return (
<div>
<button onClick={() => updateQuantity('example-id', 5)}>
Set Quantity to 5
</button>
</div>
);
};
incrementQuantity
Type: Action
Description: Function to increase the quantity of a specific item in the cart by one.
Args
- itemId (Required): The id of the item to increment.
Usage
import { useCart } from 'shopping-cart-react';
const IncrementQuantityExample = () => {
const { incrementQuantity } = useCart();
return (
<div>
<button onClick={() => incrementQuantity('example-id')}>
Increase Quantity by 1
</button>
</div>
);
};
decrementQuantity
Type: Action
Description: Function to decrease the quantity of a specific item in the cart by one.
Args
- itemId (Required): The id of the item to decrement.
Usage
import { useCart } from 'shopping-cart-react';
const DecrementQuantityExample = () => {
const { decrementQuantity } = useCart();
return (
<div>
<button onClick={() => decrementQuantity('example-id')}>
Decrease Quantity by 1
</button>
</div>
);
};
removeItemFromCart
Type: Action
Description: Function to remove a specific item from the cart.
Args
- itemId (Required): The id of the item to remove.
Usage
import { useCart } from 'shopping-cart-react';
const RemoveItemFromCartExample = () => {
const { removeItemFromCart } = useCart();
return (
<div>
<button onClick={() => removeItemFromCart('example-id')}>
Remove Item
</button>
</div>
);
};
clearCart
Type: Action
Description: Function to remove all items from the cart and reset the cart state.
Usage
import { useCart } from 'shopping-cart-react';
const ClearCartExample = () => {
const { clearCart } = useCart();
return (
<div>
<button onClick={() => clearCart()}>Clear Cart</button>
</div>
);
};
updateCartMetrics
Type: Action
Description: Function to update cart metrics like total price and item count based on the current cart state.
Usage
import { useCart } from 'shopping-cart-react';
const UpdateCartMetricsExample = () => {
const { updateCartMetrics } = useCart();
return (
<div>
<button onClick={() => updateCartMetrics()}>Update Cart Metrics</button>
</div>
);
};