Create Shopping Carts using React and Tailwind CSS
Last Updated :
27 Sep, 2024
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:
project structureUpdated 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.
Similar Reads
Create Banners using React and Tailwind CSS
We will build a responsive banner component using React and Tailwind CSS. Tailwind CSS allows us to create highly customizable and modern UI components with minimal effort. The banner will include a heading and subheading and a call to action button styled for responsiveness and accessibility. Prere
3 min read
Create Content Sections using React and Tailwind CSS
Creating well-structured content sections is crucial for any modern web application. In this article, we will walk through how to build content sections using React styled with Tailwind CSS and enhanced with React Icons. We will create a React application with multiple content sections. Each section
3 min read
Create Reviews using React and Tailwind CSS
In general, reviews, are the most essential feedback mechanisms that serve multiple purposes like User feedback, Product rating, Content rating, etc. And if we use a reviews system in our website then it also helps the new users to know about the product or the users easily. In this article, we will
4 min read
Create Buttons UI using React and Tailwind CSS
Tailwind CSS is a utility-first CSS framework that allows developers to quickly build responsive and reusable components. We'll explore how to create buttons with different styles such as primary, secondary, and disabled states, and buttons of various sizes. PrerequisitesReact JavaScriptNodeJSTailwi
2 min read
Create Team Sections Using React and Tailwind CSS
In this article, we will create a Team Section using React and Tailwind CSS. The team section will display team member information including their name role, and profile picture with a responsive and modern layout. Tailwind CSS simplifies styling by using utility first classes making the development
3 min read
Create Promo Sections using React and Tailwind CSS
Weâll learn how to create attractive Promo Sections in a React application using Tailwind CSS. Promo sections are important for highlighting special offers, announcements, or important features. With Tailwind CSS, we can easily style our components and create responsive designs. Prerequisites React
5 min read
Create FAQs using React and Tailwind CSS
A Frequently Asked Questions section is a common feature found on websites and applications that helps users find answers to common queries in an organized manner. A well-designed FAQ can improve user experience reduce support requests and provide users with quick and easy access to helpful informat
5 min read
Create Logo Clouds using React and Tailwind CSS
A Logo Cloud is a webpage section that displays logos of partners, sponsors, clients, or technologies in a visually appealing way. This component is often used to establish credibility or showcase affiliations. Using React and Tailwind CSS you can create a responsive and customizable logo cloud that
3 min read
Create Header Sections using React and Tailwind CSS
React is a JavaScript library for building UI components combined with Tailwind CSS a utility-first CSS framework that offers a flexible approach to create beautiful responsive header sections. In this article, we will walk through creating a responsive header section using React and Tailwind CSS fo
4 min read
Create Category Filters using React and Tailwind CSS
Creating a category filter in a React application allows users to filter a list of items based on selected categories. We will build a simple filtering system using React for state management and Tailwind CSS for styling and React Icons to add visual enhancements to the UI. This project will allow u
4 min read