Using a shopping cart in your React/Next application.
Tags: react, shoppingcart, nextjs, customhook
Published: 2022-05-21 22:16:18


![shopping cart in reactJs/NextJs](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/jn5hht59lll890ymn5mf.png)

This guide aims to help you handle the cart operations very easily without the need to create your own from scratch.

Now it’s time to create your shopping cart so your customer can buy multiple products at one or save them for later.
But don’t worry about the main logic of building the cart operations from zero, I already did most of the work for you.

## Requirements/Prerequisites

- IDE of your choice (code editor)
- Package manager → npm or yarn.
- Working on React or Nextjs project.
- Some knowledge of Javascript & React.

## Let’s start
first, you should install my lightweight shopping cart that gonna handle your cart operations like adding, removing, and updating your products and more …

so run the command:
`npm i react-use-shoppingcart
`or
`yarn add react-use-shoppingcart
`
after running one of the above commands, the package will be ready.

You need to import the contextProvider component into the App.js file and wrap your application in the CartContextProvider component. you can read more about the [Context](https://reactjs.org/docs/context.html) but it is not necessary right now.

import line:
`import { CartContextProvider } from 'react-use-shoppingcart';
`
<u>App.js</u>
```
import { CartContextProvider } from 'react-use-shoppingcart';
import Navbar from './components/navbar';
import Product from './components/product';
import Cart from './components/cart';
function App() {
  return (
    <div className="App">
      <CartContextProvider>
        <Navbar />
        <Cart />
        <Product />
      </CartContextProvider>
    </div>
  );
}
```
Now your application can use the cart operations from any components in your app by calling a custom hook already created for you.

So let’s assume that you have a component or a page called Product.js

firstly, you should import the useCart hook that returns an object with all the necessary stuff that gonna handle your cart logic. you can read more about [hooks](https://reactjs.org/docs/hooks-intro.html).

`import { useCart } from "react-use-shoppingcart";
`
after importing the useCart hook, now you can call it inside your component in this way:
```
const { cartItems, removeFromCart, clearCart, totalPriceCart } = useCart();
```
and also let’s assume that your products array is structured like
```
const products = [
    {
      id: 1,
      name: "jacket",
      price: 500,
      image: "path/to/image"
      ...
    },
     {
      id: 2,
      name: "jeans",
      price: 100,
      image: "path/to/image"
      ...
    },
    {
      id: 3,
      name: "t-shirt",
      price: 254,
      image: "path/to/image"
      ...
    },
  ];
```
So the product component or page will look like

<u>Product.js</u>
```
import { useCart } from "react-use-shoppingcart";

const products = [
    {
      id: 1,
      name: "jacket",
      price: 500,
      image: "path/to/image"
      ...
    },
     {
      id: 2,
      name: "jeans",
      price: 100,
      image: "path/to/image"
      ...
    },
    {
      id: 3,
      name: "t-shirt",
      price: 254,
      image: "path/to/image"
      ...
    },
  ];
  const Product = () => {
      const { addToCart } = useCart();
      return (
        <div className="container">
          {products.map((product) => {
            return (
              <div className="card" key={product.id}>
                <img
                  src={product.image}
                  alt="product image"
                />
                <h1>{product.name}</h1>
                <p className="price">{product.price}$</p>
                <p>
                  <button onClick={() => addToCart(product)}>Add to Cart</button>
                </p>
              </div>
            );
          })}
        </div>
      );
}
export default Product;
```
the code above will list all your products, and if the client clicks on “the Add to cart” button the product will be added to the cart.

after the products are added to the cart, the client needs to see his cart and manage it by removing a specific product or clearing it.

Let’s see an example of how our Cart components will look like

<u>Cart.js</u>
```
import { useCart } from "react-use-shoppingcart";
const Cart = () => {
  const { cartItems, removeFromCart, clearCart, totalPriceCart } = useCart();
  return (
    <div>
      <div className="cartContainer">
        {cartItems.map(item => {
          return (
            <div className="cart" key={item.product.id}>
              <div>
                <div>
                  {item.product.name} - {item.product.price}$: - qty:
                  {item.qty}
                </div>
              </div>
              <div>
                <div>
                  <button onClick={() => removeFromCart(item.product.id)}>
                    remove
                  </button>
                </div>
              </div>
            </div>
          );
        })}
      </div>
      <div>
        <div>Total : {totalPriceCart}</div>
        <button onClick={clearCart}>clear</button>
      </div>
    </div>
  );
};
export default Cart;
```

- `cartItems` is an array that contains existed products in the cart and is structured like
```
[ 
 {
   product:{
      id: 1,
      name: "jacket",
      price: 500,
      image: "path/to/image"
      ...
   },
   qty:5
 },
 {
   product:{
      id: 2,
      name: "blazor",
      price: 200,
      image: "path/to/image"
      ...
   },
   qty:3
 },
 ...
]
```

- `removeFromCart(producId)` is a function used to remove a specific product from the cart.
- `clearCart` is a function used to clear the cart.
- `totalPriceCart` is the total price of the existed products in the cart.

![final result of the shopping cart custom hook](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8ntn2zui8244czsqj0pi.gif)

Finally, your cart is built and ready, so your role is to create an attractive UX/UI to impress your clients.

So if you find the post helpful don’t forget to like it, and if you are an experienced developer or blogger, feel free to help me improve my package or my blogging skills.

- [react-use-shoppingcart npm package](https://www.npmjs.com/package/react-use-shoppingcart).
- [Github repository](https://github.com/abdelmoula17/react-use-shoppingcart).

Tchao!