Sign Up for Free

RunKit +

Try any Node.js package right in your browser

This is a playground to test code. It runs a full Node.js environment and already has all of npm’s 400,000 packages pre-installed, including react-use-cart with all npm packages installed. Try it out:

require("react/package.json"); // react is a peer dependency. var reactUseCart = require("react-use-cart")

This service is provided by RunKit and is not affiliated with npm, Inc or the package authors.

react-use-cart v1.2.2

React hook library for managing cart state.

react-use-cart

🛒 A lightweight cart React hook library. Demo

Quick Start

import { CartProvider, useCart } from 'react-use-cart'

function Page() {
  const { addItem } = useCart()

  const products = [
    {
      id: 1,
      name: 'Malm',
      price: 9900,
    },
    {
      id: 2,
      name: 'Nordli',
      price: 16500,
    },
    {
      id: 3,
      name: 'Kullen',
      price: 4500,
    },
  ]

  return (
    <div>
      {products.map(p => (
        <div key={p.id}>
          <button onClick={() => addItem(p)}>Add to cart</button>
        </div>
      ))}
    </div>
  )
}

function Cart() {
  const {
    isEmpty,
    totalUniqueItems,
    items,
    updateItemQuantity,
    removeItem,
  } = useCart()

  if (isEmpty) return <p>Your cart is empty</p>

  return (
    <>
      <h1>Cart ({totalUniqueItems})</h1>

      <ul>
        {items.map(item => (
          <li key={item.id}>
            {item.quantity} x {item.name} &mdash;
            <button
              onClick={() => updateItemQuantity(item.id, item.quantity - 1)}
            >
              -
            </button>
            <button
              onClick={() => updateItemQuantity(item.id, item.quantity + 1)}
            >
              +
            </button>
            <button onClick={() => removeItem(item.id)}>&times;</button>
          </li>
        ))}
      </ul>
    </>
  )
}

function App() {
  return (
    <CartProvider id="abc">
      <Page />
      <Cart />
    </CartProvider>
  )
}

Install

yarn add react-use-cart

CartProvider

You will need to wrap your application with the CartProvider component so that the useCart hook can access the cart state.

Carts are persisted across visits using localStorage.

Usage

import React from 'react'
import ReactDOM from 'react-dom'
import { CartProvider } from 'react-use-cart'

ReactDOM.render(
  <CartProvider>{/* render app/cart here */}</CartProvider>,
  document.getElementById('root')
)

Props

  • id (Required): The id for your cart
  • onItemAdd: Triggered on items added to your cart
  • onItemUpdate: Triggered on items updated in your cart
  • onItemRemove: Triggered on items removed from your cart

useCart

The useCart hook exposes all the getter/setters for your cart state.

addItem(item, quantity)

The addItem method should be used to add items to the cart.

Args

  • item (Required): An object that represents your cart item. You must provide an id and price value for new items that you add to cart.
  • quantity (optional, default: 1): The amount of items you want to add.

Usage

import { useCart } from 'react-use-cart'

const { addItem } = useCart()

const product = {
  id: 'cjld2cjxh0000qzrmn831i7rn',
  name: 'Fresh Foam 1080v9',
  brand: 'New Balance',
  color: 'Neon Emerald with Dark Neptune'
  size: 'US 9',
  width: 'B - Standard',
  sku: 'W1080LN9',
  price: 15000
}

addItem(product, 2)

updateItem(itemId, data)

The updateItem method should be used to update items in the cart.

Args

  • itemId (Required): The cart item id you want to update.
  • data (Required): The updated cart item object.

Usage

import { useCart } from 'react-use-cart'

const { updateItem } = useCart()

updateItem('cjld2cjxh0000qzrmn831i7rn', {
  size: 'UK 10',
})

updateItemQuantity(itemId, quantity)

The updateItemQuantity method should be used to update an items quantity value.

Args

  • itemId (Required): The cart item id you want to update.
  • quantity (Required): The updated cart item quantity.

Usage

import { useCart } from 'react-use-cart'

const { updateItemQuantity } = useCart()

updateItemQuantity('cjld2cjxh0000qzrmn831i7rn', 1)

removeItem(itemId)

The removeItem method should be used to remove an item from the cart.

Args

  • itemId (Required): The cart item id you want to remove.

Usage

import { useCart } from 'react-use-cart'

const { removeItem } = useCart()

removeItem('cjld2cjxh0000qzrmn831i7rn')

emptyCart()

The emptyCart() method should be used to remove all cart items, and resetting cart totals to the default 0 values.

Usage

import { useCart } from 'react-use-cart'

const { emptyCart } = useCart()

emptyCart()

items

This will return the current cart items.

Usage

import { useCart } from 'react-use-cart'

const { items } = useCart()

isEmpty

A quick and easy way to check if the cart is empty.

Usage

import { useCart } from 'react-use-cart'

const { isEmpty } = useCart()

getItem(itemId)

Get a specific cart item by id.

Args

  • itemId (Required): The id of the item you're fetching.

Usage

import { useCart } from 'react-use-cart'

const { item } = useCart()

const myItem = item('cjld2cjxh0000qzrmn831i7rn')

inCart(itemId)

Quickly check if an item is in the cart.

Args

  • itemId (Required): The id of the item you're looking for.

Usage

import { useCart } from 'react-use-cart'

const { inCart } = useCart()

inCart('cjld2cjxh0000qzrmn831i7rn') ? 'In cart' : 'Not in cart'

totalItems

This method returns the totaly quantity of items in the cart.

Usage

import { useCart } from 'react-use-cart'

const { totalItems } = useCart()

totalUniqueItems

This method returns the total unique items in the cart.

Usage

import { useCart } from 'react-use-cart'

const { totalUniqueItems } = useCart()

cartTotal

This method returns the total value of all items in the cart.

Usage

import { useCart } from 'react-use-cart'

const { cartTotal } = useCart()
RunKit is a free, in-browser JavaScript dev environment for prototyping Node.js code, with every npm package installed. Sign up to share your code.
Sign Up for Free