use-shopping-cart

addItem()

addItem()

To add a product to the cart, use useShoppingCart()'s addItem(product) method. It takes in your product object which must be in the following shape:

KeyValue (type)Required
nameName of the product to be shown on the Checkout page (string)Yes in CheckoutSession mode
descriptiondescription to be shown on the Stripe Checkout page (string)No
skuA unique identifier (stock keeping unit) for this item (string)Yes
pricePrice in smallest currency unit (number)Yes
currencyISO currency code (string)Yes
imageImage to be shown on the Stripe Checkout page (string)No
const products = [
{
name: 'Bananas',
description: 'Yummy yellow fruit',
sku: 'sku_banana001',
price: 400,
currency: 'USD',
image: 'https://my-image.com/banana.jpg'
}
]

You can add an optional quantity param, to add by that number. addItem(product, 10) for example would add by 10.

 Bananas
Bananas

$4.00

{}
export function Product({ product }) {
const { addItem } = useShoppingCart()
/* A helper function that turns the price into a readable format */
const price = formatCurrencyString({
value: product.price,
currency: product.currency,
language: 'en-US'
})
return (
<article
style={{
display: 'flex',
flexDirection: 'column',
justifyContent: 'center',
alignItems: 'center',
width: '50%'
}}
>
<figure style={{ textAlign: 'center' }}>
<img
style={{ height: 200, width: 250 }}
src={product.image}
alt={` ${product.name}`}
/>
<figcaption>{product.name}</figcaption>
</figure>
<p>{price}</p>
{/* Adds the item to the cart */}
<section
style={{
display: 'flex',
justifyContent: 'space-evenly',
width: '100%'
}}
>
<button
onClick={() => addItem(product)}
aria-label={`Add ${product.name} to your cart`}
style={{ height: 50, width: 100, marginBottom: 30 }}
>
Add to cart
</button>
<button
onClick={() => addItem(product, 10)}
aria-label={`Add 10 ${product.name} to your cart`}
style={{ height: 50, width: 100, marginBottom: 30 }}
>
Add 10 to cart
</button>
</section>
</article>
)
}
Edit this page on GitHub