← Back to all tutorials

How to add items to your cart with Tailwind CSS and Alpinejs

Cart page with items added to the cart
Published on May 07 2024 by Michael Andreuzza

Here we so with a simple cart example using Tailwind CSS and Alpinejs. We’ll be using the x-data directive to create a data object that holds the cart items and their quantities and the x-for directive to iterate over the items and display them in a list.

What are add to cart buttons and what do they do?

Add to cart buttons are used to add items to the cart. They typically have a “Add to Cart” text or icon next to them. When clicked, the button will add the item to the cart and display the total price of the cart or how many items are in the cart.

Use cases:

  • Shopping carts: A shopping cart is a list of items that a customer can add to their cart and then checkout.
  • Product listings: A product listing is a list of products that a customer can add to their cart and then checkout.
  • Online stores: An online store is a website that sells products and allows customers to add them to their cart and then checkout.
  • E-commerce websites: An e-commerce website is a website that sells products and allows customers to add them to their cart and then checkout.

This is the structure of the project: Understanding the code:

  • x-data="{ cart: [], products: [{ id: 1, name: 'Tomatoes', price: 10 }, { id: 2, name: 'Carrots', price: 5 }] }": This is the data object that holds the cart items and their quantities.
  • addToCart(product): This is a function that adds a product to the cart.
  • removeFromCart(index): This is a function that removes an item from the cart.
  • increaseQuantity(index): This is a function that increases the quantity of an item in the cart.
  • decreaseQuantity(index): This is a function that decreases the quantity of an item in the cart.
  • totalPrice(): This is a function that calculates the total price of the cart items.
  • x-for="product in products": This is a directive that iterates over the products in the products array and displays them in a list.
  • x-text="product.name": This is a directive that displays the name of each product in the list.
  • x-text="'$' + product.price": This is a directive that displays the price of each product in the list.
  • <button @click="addToCart(product)">Add to Cart</button>: This is a button that adds a product to the cart when clicked.
  • x-for="(item, index) in cart": This is a directive that iterates over the items in the cart array and displays them in a list.
  • x-text="${item.name} x${item.quantity}": This is a directive that displays the name and quantity of each item in the list.
  • x-text="item.price * item.quantity": This is a directive that displays the price of each item in the list.
  • <button @click="increaseQuantity(index)">+</button>: This is a button that increases the quantity of an item in the cart when clicked.
  • <button @click="decreaseQuantity(index)">-</button>: This is a button that decreases the quantity of an item in the cart when clicked.
  • <button @click="removeFromCart(index)">Remove</button>: This is a button that removes an item from the cart when clicked.
  • x-text="totalPrice()": This is a directive that displays the total price of the cart items.

Classes are removed for brevity, but I’ll keep those classes relveant to the tutorial.

<div
  x-data="{
        cart: [],
        products: [
            { id: 1, name: 'Tomatoes', price: 10 },
            // Add more products here
        ],
        addToCart(product) {
            let existingItem = this.cart.find(item => item.id === product.id);
            if (existingItem) {
                existingItem.quantity++;
            } else {
                this.cart.push({ ...product, quantity: 1 });
            }
        },
        removeFromCart(index) {
            this.cart.splice(index, 1);
        },
        increaseQuantity(index) {
            this.cart[index].quantity++;
        },
        decreaseQuantity(index) {
            if (this.cart[index].quantity > 1) {
                this.cart[index].quantity--;
            } else {
                this.removeFromCart(index);
            }
        },
        totalPrice() {
            return this.cart.reduce((total, item) => total + item.price * item.quantity, 0);
        }
    }">
  <!-- Product List -->
  <ul>
    <template
      x-for="product in products"
      :key="product.id">
      <li>
        <div>
          <span x-text="product.name"></span> - <span
            x-text="'$' + product.price"></span>
        </div>
        <button @click="addToCart(product)">Add to Cart</button>
      </li>
    </template>
  </ul>

  <!-- Cart -->
  <div>
    <h4>Your items</h4>
    <ul>
      <template
        x-for="(item, index) in cart"
        :key="index">
        <li>
          <span x-text="`${item.name} x${item.quantity}`"></span> - $<span
            x-text="item.price * item.quantity"
          ></span>
          <button
            @click="increaseQuantity(index)"
            >+</button
          >
          <button
            @click="decreaseQuantity(index)"
            >-</button
          >
          <button
            @click="removeFromCart(index)"
            >Remove</button
          >
        </li>
      </template>
    </ul>
    <div>Total Price: $<span x-text="totalPrice()"></span></div>
  </div>
</div>

Conclusion

This is a simple cart example that demonstrates how to use Tailwind CSS and Alpinejs to create a cart with items and quantities. It’s a great starting point for building more complex carts and checkout forms. Remember to add validation and error handling to make sure the cart is always up-to-date, accurate, secure and accessible.

Hope you enjoyed this tutorial and have a great day!

/Michael Andreuzza

Did you like this tutorial? Please share it with your friends!

Reviews and opinions

  • "I bought a beautiful theme from Lexington a couple weeks ago. I didn't know Astro at the time, but Michael helped me get set up and really went above and beyond with his support. Now I'm happily redoing my site to look gorgeous with his template."

    Stuart

    Stuart

    Creator of saasydb.com

  • "Michael is one of the best designers on Twitter, would highly recommend his Lexington Themes if you want something in tailwind that doesn’t look the same as everyone else!"

    Alex Hughes

    Alex Hughes

    letsloopin.com

Get lifetime access to every theme available today for $199 and own them forever. Plus, new themes, lifetime updates, use on unlimited projects and enjoy lifetime support.

No subscription required!

Lexington

Beautifully designed HTML, Astro.js and Tailwind themes! Save months of time and build your startup landing page in minutes.