Open In App

Create Shopping Carts using React and Tailwind CSS

Last Updated : 27 Sep, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

We will create a Shopping Cart using React and Tailwind CSS, allowing users to browse through products, add items to their cart, view their cart, and adjust quantities. We will enhance the user experience by integrating React Icons for aesthetic and functional icons like Add to Cart or Remove Item.

Prerequisites

Approach

  • Begin by setting up a React application to serve as the foundation for your shopping cart. This involves installing necessary packages like Tailwind CSS for styling and React Icons for UI enhancements.
  • Implement state management to handle the cart's contents. Use React's useState or Context API to maintain the cart’s state globally, allowing for easy updates when products are added or removed.
  • Focus on making the application responsive and accessible. Tailwind CSS aids in creating a layout that adapts to different devices, while thoughtful use of semantic HTML improves accessibility.
  • Once the core functionality is implemented, test the application to ensure all features work seamlessly. Gather feedback and iterate on the design and functionality based on user experience.

Steps to Create Shopping Carts

Step 1: Set up a React Application

npx create-react-app react-app
cd react-app

Step 2: Install Tailwind CSS using the command

npm install -D tailwindcss postcss autoprefixer
npx tailwindcss init -p

Step 3: Configure the tailwind paths in your tailwind.config.js file.

module.exports = {
content: ["./src/**/*.{js,jsx,ts,tsx}"],
theme: {
extend: {
colors: {
primaryGreen: "#4CAF50", // Green
primaryBlack: "#000000", // Black
primaryWhite: "#FFFFFF", // White
}
},
},
plugins: [],
}

Step 4: Add tailwind directives to your index.css file.

@tailwind base;
@tailwind components;
@tailwind utilities;

body {

margin: 0;
font-family: 'Times New Roman', Times, serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}

code {
font-family: source-code-pro, Menlo, Monaco, Consolas, 'Courier New',
monospace;
}

h2 {
margin-top: 2rem;
/* Adjust top margin for spacing */
}

Step 5: Install the React-Icons

npm install react-icons

Project Structure:

Screenshot-2024-09-12-114329
project structure

Updated dependencies:

"dependencies": {
"@testing-library/jest-dom": "^5.17.0",
"@testing-library/react": "^13.4.0",
"@testing-library/user-event": "^13.5.0",
"react": "^18.3.1",
"react-dom": "^18.3.1",
"react-icons": "^5.3.0",
"react-scripts": "5.0.1",
"web-vitals": "^2.1.4"
}

Example: This example demonstrates the creation of Shopping Carts using React and Tailwind CSS:

JavaScript
// App.js

import React, { useState } from 'react';
import { FaCartPlus, FaTrashAlt } from 'react-icons/fa';

function App() {
    // Dummy product data
    const products = [
        { id: 1, name: 'Green Sneakers', price: 50, image: 
        'https://via.placeholder.com/150' },
        { id: 2, name: 'Black Hat', price: 30, image: 
        'https://via.placeholder.com/150' },
        { id: 3, name: 'White T-shirt', price: 25, image: 
        'https://via.placeholder.com/150' },
        { id: 4, name: 'Green Jacket', price: 60, image: 
        'https://via.placeholder.com/150' },
    ];

    // State to manage cart items
    const [cartItems, setCartItems] = useState([]);

    // Add product to the cart
    const addToCart = (product) => {
        setCartItems((prevItems) => {
            const itemExists = prevItems.find((item) => item.id === product.id);
            if (itemExists) {
                return prevItems.map((item) =>
                    item.id === product.id ? { ...item, quantity: 
                    item.quantity + 1 } : item
                );
            } else {
                return [...prevItems, { ...product, quantity: 1 }];
            }
        });
    };

    // Remove product from the cart
    const removeFromCart = (id) => {
        setCartItems((prevItems) => prevItems.filter((item) => 
        item.id !== id));
    };

    // Update product quantity in the cart
    const updateQuantity = (id, newQuantity) => {
        setCartItems((prevItems) =>
            prevItems.map((item) =>
                item.id === id ? { ...item, quantity: newQuantity > 0 ? 
                newQuantity : 1 } : item
            )
        );
    };

    // Calculate total price
    const total = cartItems.reduce((acc, item) => acc + item.price * 
    item.quantity, 0);

    return (
        <div className="min-h-screen bg-white text-white p-4">
            <div className="container mx-auto">
                <h1 className="text-3xl font-bold mb-4 text-green-600 
                text-center">Shopping Cart</h1>

                {/* Product List */}
                <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 
                gap-6 mb-8">
                    {products.map((product) => (
                        <div key={product.id} className="border p-4 rounded-lg 
                        shadow-lg hover:shadow-2xl transition-shadow duration-200">
                            <img src={product.image} alt={product.name} 
                            className="h-40 w-full object-cover mb-4 rounded-lg" />
                            <h2 className="text-lg font-semibold mb-2 text-white">
                            {product.name}</h2>
                            <p className="text-green-600 font-semibold">$
                            {product.price}</p>
                            <button
                                onClick={() => addToCart(product)}
                                className="mt-3 bg-green-600 text-white px-4
                                py-2 rounded-lg flex items-center gap-2 
                                hover:bg-green-700 transition-colors"
                            >
                                <FaCartPlus /> Add to Cart
                            </button>
                        </div>
                    ))}
                </div>

                {/* Cart Section */}
                <div className="border p-4 rounded-lg shadow-lg bg-green-500">
                    <h2 className="text-2xl font-bold mb-4 text-white">Your Cart</h2>
                    {cartItems.length === 0 ? (
                        <p className='text-white'>Your cart is empty</p>
                    ) : (
                        <>
                            {cartItems.map((item) => (
                                <div key={item.id} className="flex justify-between 
                                items-center my-4 border-b pb-4">
                                    <img src={item.image} alt={item.name} 
                                    className="h-20 w-20 object-cover rounded-lg" />
                                    <div className="flex flex-col">
                                        <h3 className="text-lg font-semibold">
                                        {item.name}</h3>
                                        <p className="text-white font-semibold">
                                        ${item.price}</p>
                                        <div className="flex items-center gap-2 mt-2">
                                            <button
                                                onClick={() => updateQuantity
                                                (item.id, item.quantity - 1)}
                                                className="bg-white px-2 py-1 
                                                rounded text-green-600"
                                            >
                                                -
                                            </button>
                                            <span>{item.quantity}</span>
                                            <button
                                                onClick={() => updateQuantity
                                                (item.id, item.quantity + 1)}
                                                className="bg-white px-2 py-1
                                                rounded text-green-600"
                                            >
                                                +
                                            </button>
                                        </div>
                                    </div>
                                    <button onClick={() => removeFromCart(item.id)} 
                                    className="text-white">
                                        <FaTrashAlt size={20} />
                                    </button>
                                </div>
                            ))}
                            <div className="flex justify-between items-center mt-6">
                                <h3 className="text-xl font-bold text-white">Total:</h3>
                                <span className="text-xl font-bold text-white">$
                                {total.toFixed(2)}</span>
                            </div>
                        </>
                    )}
                </div>
            </div>
        </div>
    );
}

export default App;

To start the Application run the following command.

npm start

Output:

Conclusion

In this article we have successfully built a shopping cart using React and Tailwind CSS and React Icons. This setup provides a scalable and reusable solution for handling product lists and cart operations and real-time updates in the user interface. React and Tailwind CSS offers flexibility in development and styling while React Icons adds a touch of elegance to the user interface.


Next Article

Similar Reads