use-shopping-cart

Getting started

Table of Contents

Installation

npm install --save @stripe/stripe-js use-shopping-cart
or
yarn add @stripe/stripe-js use-shopping-cart

The package needs to be configured with your account's secret key, which is available in the Stripe Dashboard. Require it with the key's value.

At the root level of your app, wrap your root component in the <CartProvider />

import ReactDOM from 'react-dom'
import { loadStripe } from '@stripe/stripe-js'
import { CartProvider } from 'use-shopping-cart'
import App from './App'
// Remember to add your public Stripe key
const stripePromise = loadStripe(process.env.REACT_APP_STRIPE_API_PUBLIC)
ReactDOM.render(
<CartProvider
stripe={stripePromise}
successUrl="stripe.com"
cancelUrl="twitter.com/dayhaysoos"
currency="USD"
allowedCountries={['US', 'GB', 'CA']}
billingAddressCollection={true}
>
<App />
</CartProvider>,
document.getElementById('root')
)

Using the hook

The hook useShoppingCart() provides several utilities and pieces of data for you to use in your application. The examples below won't cover every part of the useShoppingCart() API but you can look at the API below.

import { useShoppingCart } from 'use-shopping-cart'
import { Product } from './Product'
import { CartItems } from './CartItems'
const productData = [
{
name: 'Bananas',
sku: 'sku_GBJ2Ep8246qeeT',
price: 400,
image: 'https://www.fillmurray.com/300/300',
currency: 'USD'
},
{
name: 'Tangerines',
sku: 'sku_GBJ2WWfMaGNC2Z',
price: 100,
image: 'https://www.fillmurray.com/300/300',
currency: 'USD'
}
]
export function App() {
/* Gets the totalPrice and a method for redirecting to stripe */
const { totalPrice, redirectToCheckout, cartCount } = useShoppingCart()
return (
<div>
{/* Renders the products */}
{productData.map((product) => (
<Product product={product} />
))}
{/* This is where we'll render our cart */}
<p>Number of Items: {cartCount}</p>
<p>Total: {totalPrice()}</p>
<CartItems />
{/* Redirects the user to Stripe */}
<button onClick={() => redirectToCheckout()}>Checkout</button>
</div>
)
}

Once you have successfully installed stripe, use-shopping-cart, and wrapped your root component with <CartProvider>, you are ready to go! 🚀

⚠️ HEADS UP!

You may not be able to see the SKUs section in your products on Stripe but a Prices section instead. If that's the case, you can use the price ID (i.e. price_abcd1234) as the sku property in your inventory.

const productData = [
{
name: 'Bananas',
sku: 'price_GBJ2Ep8246qeeT', // 👈
price: 400,
image: 'https://www.fillmurray.com/300/300',
currency: 'USD'
}
]
Edit this page on GitHub