qty shouldn't be larger than selectedSize.qty (if there is any size) or…
- User
qty shouldn't be larger than selectedSize.qty (if there is any size) or selectedColor.qty (if there is any color) also if the qty is 0, show out of stock for selected size or selected color. 'use client';
import React, { useState, useEffect, useCallback, useMemo } from 'react'; import { motion, AnimatePresence } from 'framer-motion'; import { Minus, Plus, ShoppingCart } from 'lucide-react'; import { useNotification } from '@/components/NotificationContext'; import '@/components/NotificationStyles.css'; import Link from 'next/link';
const formatPrice = (price) => { if (price == null || price === Infinity) return 'N/A'; const formattedPrice = price >= 10000 ? price.toLocaleString() : price.toString(); return
${formattedPrice} IQD; };const ProductModal = ({ isOpen, onClose, productData }) => { const [selectedSize, setSelectedSize] = useState(null); const [quantity, setQuantity] = useState(1); const [isInCart, setIsInCart] = useState(false); const { addNotification } = useNotification();
const product = productData.product; // Compute total price dynamically const totalPrice = useMemo(() => { return selectedSize ? parseFloat(selectedSize.price) * quantity : 0; }, [selectedSize, quantity]); // Check if the product is in the cart const checkIfInCart = useCallback(() => { try { const cart = JSON.parse(localStorage.getItem('cart')) || []; const isItemInCart = cart.some( (item) => item.product_id === product.id && item.size_id === selectedSize?.id ); setIsInCart(isItemInCart); } catch (error) { console.error('Error accessing localStorage:', error); setIsInCart(false); } }, [product.id, selectedSize]); // Set default selected size on product change useEffect(() => { if (product?.sizes?.length > 0) { setSelectedSize(product.sizes[0]); } }, [product]); // Check if the product is in the cart whenever selectedSize changes useEffect(() => { checkIfInCart(); }, [selectedSize, checkIfInCart]); // Handle adding product to cart const handleAddToCart = useCallback(() => { if (!selectedSize) return; const cartItem = { product_id: product.id, size_id: selectedSize.id, qty: quantity, price: selectedSize.price, }; try { const cart = JSON.parse(localStorage.getItem('cart')) || []; const existingItemIndex = cart.findIndex( (item) => item.product_id === cartItem.product_id && item.size_id === cartItem.size_id ); if (existingItemIndex > -1) { cart[existingItemIndex].qty += quantity; } else { cart.push(cartItem); } localStorage.setItem('cart', JSON.stringify(cart)); setIsInCart(true); addNotification('success', 'Added to cart successfully'); } catch (error) { console.error('Error updating cart:', error); addNotification('error', 'Failed to add to cart'); } }, [product.id, selectedSize, quantity, addNotification]); if (!isOpen || !product) return null; return ( <AnimatePresence> <motion.div initial={{ opacity: 0 }} animate={{ opacity: 1 }} exit={{ opacity: 0 }} className="fixed inset-0 bg-black bg-opacity-30 flex items-end justify-center z-50" onClick={onClose} aria-modal="true" role="dialog" > <motion.div initial={{ y: '100%' }} animate={{ y: 0 }} exit={{ y: '100%' }} transition={{ type: 'spring', damping: 25, stiffness: 500 }} className="bg-white rounded-t-3xl w-full p-6 relative" onClick={(e) => e.stopPropagation()} > <div className="w-9 h-1 bg-[#00003C] opacity-70 rounded-full mx-auto mb-6" /> <h2 className="text-xl mb-4 font-sans">{product.name}</h2> {product.has_size && ( <div className="mb-4"> <label htmlFor="size-select" className="sr-only"> Select Size </label> <select id="size-select" value={selectedSize ? selectedSize.id : ''} onChange={(e) => setSelectedSize( product.sizes.find( (size) => size.id.toString() === e.target.value ) ) } className="w-44 p-2 border border-[rgba(105,92,92,0.5)] rounded-lg font-serif text-lg focus:outline-none focus:ring-2 focus:ring-blue-500" > <option value="" disabled> Select a Size </option> {product.sizes.map((size) => ( <option key={size.id} value={size.id}> {size.name} </option> ))} </select> {!selectedSize && ( <p className="text-[#C91C1C] text-xs mt-2 font-sans"> Please choose Size </p> )} </div> )} {product.has_color && product.colors && product.colors.length > 0 && ( <div className="mb-6"> <h3 className="text-xl font-medium mb-2 font-sans">Color</h3> <div className="flex space-x-5 mb-2"> {product.colors.map((color) => ( <button key={color.id} className={`w-20 h-20 rounded-full border-2 ${ selectedSize && selectedSize.color_id === color.id ? 'border-[rgba(105,92,92,0.5)]' : 'border-transparent' } flex items-center justify-center focus:outline-none focus:ring-2 focus:ring-blue-500`} aria-label={`Select color ${color.name}`} onClick={() => { // Assuming color selection affects selectedSize // If not, consider adding a separate state for selectedColor }} > <div className="w-15 h-15 rounded-full" style={{ backgroundColor: color.hex }} /> </button> ))} </div> <div className="flex justify-between px-2"> {product.colors.map((color) => ( <span key={color.id} className="text-sm font-serif"> {color.name} </span> ))} </div> </div> )} <div className="flex font-serif justify-between items-center mb-6"> <p className="text-lg font-medium">{formatPrice(totalPrice)}</p> <div className="flex items-center space-x-4"> <button className="w-8 h-8 rounded-full border border-gray-300 flex items-center justify-center focus:outline-none focus:ring-2 focus:ring-blue-500 disabled:opacity-50" onClick={() => setQuantity((prev) => Math.max(1, prev - 1))} disabled={quantity <= 1} aria-label="Decrease quantity" > <Minus className="w-4 h-4 text-[#3B5345]" /> </button> <span className="text-lg">{quantity}</span> <button className="w-8 h-8 rounded-full border border-gray-300 flex items-center justify-center focus:outline-none focus:ring-2 focus:ring-blue-500" onClick={() => setQuantity((prev) => prev + 1)} aria-label="Increase quantity" > <Plus className="w-4 h-4 text-[#3B5345]" /> </button> </div> </div> <div className="flex font-serif space-x-4"> {isInCart ? ( <Link href="/cart" prefetch={false} className="flex-1 font-serif bg-[rgba(59,83,69,0.05)] text-[#3B5345] py-3 rounded-lg font-medium text-base md:text-lg flex items-center justify-center transition duration-300 border border-[#3B5345] hover:bg-[rgba(59,83,69,0.1)]" > <ShoppingCart className="mr-2" /> Buy Now </Link> ) : ( <button className={`flex-1 ${ selectedSize ? 'bg-[#3B5345] text-white hover:bg-[#2d4233]' : 'bg-gray-300 text-gray-500 cursor-not-allowed' } py-3 rounded-lg font-medium text-base md:text-lg flex items-center justify-center transition duration-300`} onClick={handleAddToCart} disabled={!selectedSize} aria-label="Add to cart" > <ShoppingCart className="mr-2" /> Add To Cart </button> )} <button className="flex-1 bg-gray-200 text-gray-800 py-3 rounded-lg font-medium text-base md:text-lg hover:bg-gray-300 transition duration-300" onClick={onClose} aria-label="Close modal" > Close </button> </div> </motion.div> </motion.div> </AnimatePresence> );};
export default React.memo(ProductModal);
- Assistant
To implement the desired functionality—restricting the quantity (
qty) based on the selected size or color and displaying an "Out of Stock" message when applicable—you need to incorporate additional state management and conditional rendering in yourProductModalcomponent.Below, I'll guide you through the necessary modifications and enhancements to achieve this behavior:
-
State Management for Selected Color:
- Introduce a
selectedColorstate to track the user's color choice. - Ensure that both size and color selections impact the available quantity.
- Introduce a
-
Determining Maximum Available Quantity (
maxQty):- Compute
maxQtybased on the selected size and/or color. - If both size and color are selected, and if their combination defines a unique variant, ensure that
maxQtyreflects this specific variant's stock. - If only size or color is selected, use their respective
qty.
- Compute
-
Restricting Quantity Selection:
- Ensure that the user cannot select a quantity greater than
maxQty. - Disable the "Increase" button if
quantityreachesmaxQty. - Prevent adding to the cart if
maxQtyis0.
- Ensure that the user cannot select a quantity greater than
-
Displaying "Out of Stock":
- When
maxQtyis0, show an "Out of Stock" message based on the selected size or color.
- When
-
Handling Variants (If Applicable):
- If your product data structure includes variants that are combinations of size and color, adjust the logic accordingly to fetch the correct
qtyfor the selected combination.
- If your product data structure includes variants that are combinations of size and color, adjust the logic accordingly to fetch the correct
Below is the revised
ProductModalcomponent with these enhancements:'use client'; import React, { useState, useEffect, useCallback, useMemo } from 'react'; import { motion, AnimatePresence } from 'framer-motion'; import { Minus, Plus, ShoppingCart } from 'lucide-react'; import { useNotification } from '@/components/NotificationContext'; import '@/components/NotificationStyles.css'; import Link from 'next/link'; const formatPrice = (price) => { if (price == null || price === Infinity) return 'N/A'; const formattedPrice = price >= 10000 ? price.toLocaleString() : price.toString(); return `${formattedPrice} IQD`; }; const ProductModal = ({ isOpen, onClose, productData }) => { const [selectedSize, setSelectedSize] = useState(null); const [selectedColor, setSelectedColor] = useState(null); const [quantity, setQuantity] = useState(1); const [isInCart, setIsInCart] = useState(false); const { addNotification } = useNotification(); const product = productData.product; // Compute maxQty based on selected size and/or color const maxQty = useMemo(() => { let sizeQty = selectedSize ? selectedSize.qty : Infinity; let colorQty = selectedColor ? selectedColor.qty : Infinity; // Assuming that if both size and color are selected, the available qty is the minimum of both return Math.min(sizeQty, colorQty); }, [selectedSize, selectedColor]); // Adjust quantity if it exceeds maxQty useEffect(() => { if (quantity > maxQty) { setQuantity(maxQty); } if (maxQty === 0) { setQuantity(0); } else if (quantity < 1 && maxQty > 0) { setQuantity(1); } }, [maxQty, quantity]); // Compute total price dynamically const totalPrice = useMemo(() => { // Assuming that price is based on size; adjust if based on color or variant return selectedSize ? parseFloat(selectedSize.price) * quantity : 0; }, [selectedSize, quantity]); // Check if the product is in the cart const checkIfInCart = useCallback(() => { try { const cart = JSON.parse(localStorage.getItem('cart')) || []; const isItemInCart = cart.some( (item) => item.product_id === product.id && item.size_id === selectedSize?.id && item.color_id === selectedColor?.id ); setIsInCart(isItemInCart); } catch (error) { console.error('Error accessing localStorage:', error); setIsInCart(false); } }, [product.id, selectedSize, selectedColor]); // Set default selected size and color on product change useEffect(() => { if (product?.sizes?.length > 0) { setSelectedSize(product.sizes[0]); } else { setSelectedSize(null); } if (product?.colors?.length > 0) { setSelectedColor(product.colors[0]); } else { setSelectedColor(null); } }, [product]); // Check if the product is in the cart whenever selectedSize or selectedColor changes useEffect(() => { checkIfInCart(); }, [selectedSize, selectedColor, checkIfInCart]); // Handle adding product to cart const handleAddToCart = useCallback(() => { if ((!selectedSize && product.has_size) || (!selectedColor && product.has_color)) { addNotification('error', 'Please select the required options'); return; } if (maxQty === 0) { addNotification('error', 'Selected option is out of stock'); return; } const cartItem = { product_id: product.id, size_id: selectedSize ? selectedSize.id : null, color_id: selectedColor ? selectedColor.id : null, qty: quantity, price: selectedSize ? selectedSize.price : product.price, }; try { const cart = JSON.parse(localStorage.getItem('cart')) || []; const existingItemIndex = cart.findIndex( (item) => item.product_id === cartItem.product_id && item.size_id === cartItem.size_id && item.color_id === cartItem.color_id ); if (existingItemIndex > -1) { const newQty = cart[existingItemIndex].qty + quantity; if (newQty > maxQty) { addNotification('error', `Cannot add more than ${maxQty} items`); return; } cart[existingItemIndex].qty = newQty; } else { if (quantity > maxQty) { addNotification('error', `Cannot add more than ${maxQty} items`); return; } cart.push(cartItem); } localStorage.setItem('cart', JSON.stringify(cart)); setIsInCart(true); addNotification('success', 'Added to cart successfully'); } catch (error) { console.error('Error updating cart:', error); addNotification('error', 'Failed to add to cart'); } }, [product, selectedSize, selectedColor, quantity, addNotification, maxQty]); if (!isOpen || !product) return null; return ( <AnimatePresence> <motion.div initial={{ opacity: 0 }} animate={{ opacity: 1 }} exit={{ opacity: 0 }} className="fixed inset-0 bg-black bg-opacity-30 flex items-end justify-center z-50" onClick={onClose} aria-modal="true" role="dialog" > <motion.div initial={{ y: '100%' }} animate={{ y: 0 }} exit={{ y: '100%' }} transition={{ type: 'spring', damping: 25, stiffness: 500 }} className="bg-white rounded-t-3xl w-full p-6 relative" onClick={(e) => e.stopPropagation()} > <div className="w-9 h-1 bg-[#00003C] opacity-70 rounded-full mx-auto mb-6" /> <h2 className="text-xl mb-4 font-sans">{product.name}</h2> {product.has_size && ( <div className="mb-4"> <label htmlFor="size-select" className="sr-only"> Select Size </label> <select id="size-select" value={selectedSize ? selectedSize.id : ''} onChange={(e) => setSelectedSize( product.sizes.find( (size) => size.id.toString() === e.target.value ) ) } className="w-44 p-2 border border-[rgba(105,92,92,0.5)] rounded-lg font-serif text-lg focus:outline-none focus:ring-2 focus:ring-blue-500" > <option value="" disabled> Select a Size </option> {product.sizes.map((size) => ( <option key={size.id} value={size.id}> {size.name} </option> ))} </select> {!selectedSize && ( <p className="text-[#C91C1C] text-xs mt-2 font-sans"> Please choose Size </p> )} </div> )} {product.has_color && product.colors && product.colors.length > 0 && ( <div className="mb-6"> <h3 className="text-xl font-medium mb-2 font-sans">Color</h3> <div className="flex space-x-5 mb-2"> {product.colors.map((color) => ( <button key={color.id} className={`w-20 h-20 rounded-full border-2 ${ selectedColor && selectedColor.id === color.id ? 'border-[rgba(105,92,92,0.5)]' : 'border-transparent' } flex items-center justify-center focus:outline-none focus:ring-2 focus:ring-blue-500`} aria-label={`Select color ${color.name}`} onClick={() => setSelectedColor(color)} > <div className="w-15 h-15 rounded-full" style={{ backgroundColor: color.hex }} /> </button> ))} </div> <div className="flex justify-between px-2"> {product.colors.map((color) => ( <span key={color.id} className="text-sm font-serif"> {color.name} </span> ))} </div> {!selectedColor && ( <p className="text-[#C91C1C] text-xs mt-2 font-sans"> Please choose Color </p> )} </div> )} {/* Display Out of Stock message */} {maxQty === 0 && ( <div className="mb-4"> <p className="text-red-600 font-semibold text-center"> Out of Stock </p> </div> )} <div className="flex font-serif justify-between items-center mb-6"> <p className="text-lg font-medium">{formatPrice(totalPrice)}</p> <div className="flex items-center space-x-4"> <button className="w-8 h-8 rounded-full border border-gray-300 flex items-center justify-center focus:outline-none focus:ring-2 focus:ring-blue-500 disabled:opacity-50" onClick={() => setQuantity((prev) => Math.max(0, prev - 1))} disabled={quantity <= 0} aria-label="Decrease quantity" > <Minus className="w-4 h-4 text-[#3B5345]" /> </button> <span className="text-lg">{quantity}</span> <button className="w-8 h-8 rounded-full border border-gray-300 flex items-center justify-center focus:outline-none focus:ring-2 focus:ring-blue-500" onClick={() => setQuantity((prev) => Math.min(prev + 1, maxQty))} disabled={quantity >= maxQty} aria-label="Increase quantity" > <Plus className="w-4 h-4 text-[#3B5345]" /> </button> </div> </div> <div className="flex font-serif space-x-4"> {isInCart ? ( <Link href="/cart" prefetch={false} className="flex-1 font-serif bg-[rgba(59,83,69,0.05)] text-[#3B5345] py-3 rounded-lg font-medium text-base md:text-lg flex items-center justify-center transition duration-300 border border-[#3B5345] hover:bg-[rgba(59,83,69,0.1)]" > <ShoppingCart className="mr-2" /> Buy Now </Link> ) : ( <button className={`flex-1 ${ selectedSize || selectedColor ? 'bg-[#3B5345] text-white hover:bg-[#2d4233]' : 'bg-gray-300 text-gray-500 cursor-not-allowed' } py-3 rounded-lg font-medium text-base md:text-lg flex items-center justify-center transition duration-300`} onClick={handleAddToCart} disabled={!selectedSize && product.has_size || !selectedColor && product.has_color || maxQty === 0} aria-label="Add to cart" > <ShoppingCart className="mr-2" /> Add To Cart </button> )} <button className="flex-1 bg-gray-200 text-gray-800 py-3 rounded-lg font-medium text-base md:text-lg hover:bg-gray-300 transition duration-300" onClick={onClose} aria-label="Close modal" > Close </button> </div> </motion.div> </motion.div> </AnimatePresence> ); }; export default React.memo(ProductModal);Detailed Explanation of Changes
-
State for
selectedColor:const [selectedColor, setSelectedColor] = useState(null);- Added
selectedColorto manage the user's color selection.
- Added
-
Updating Color Selection Logic:
onClick={() => setSelectedColor(color)}- Updated the color selection buttons to set the
selectedColorstate when a color is selected.
- Updated the color selection buttons to set the
-
Computing
maxQty:const maxQty = useMemo(() => { let sizeQty = selectedSize ? selectedSize.qty : Infinity; let colorQty = selectedColor ? selectedColor.qty : Infinity; // If both size and color are selected, take the minimum of both return Math.min(sizeQty, colorQty); }, [selectedSize, selectedColor]);maxQtyis determined based on the selected size and color.- If both are selected, it takes the minimum of their available quantities to ensure that neither option is oversold.
-
Adjusting
quantityBased onmaxQty:useEffect(() => { if (quantity > maxQty) { setQuantity(maxQty); } if (maxQty === 0) { setQuantity(0); } else if (quantity < 1 && maxQty > 0) { setQuantity(1); } }, [maxQty, quantity]);- Ensures that
quantitynever exceedsmaxQtyand handles cases wheremaxQtyis0.
- Ensures that
-
Displaying "Out of Stock":
{maxQty === 0 && ( <div className="mb-4"> <p className="text-red-600 font-semibold text-center"> Out of Stock </p> </div> )}- Conditionally renders an "Out of Stock" message when
maxQtyis0.
- Conditionally renders an "Out of Stock" message when
-
Restricting Quantity Selection Buttons:
<button ... onClick={() => setQuantity((prev) => Math.max(0, prev - 1))} disabled={quantity <= 0} ... > <Minus ... /> </button> ... <button ... onClick={() => setQuantity((prev) => Math.min(prev + 1, maxQty))} disabled={quantity >= maxQty} ... > <Plus ... /> </button>- The "Decrease" button allows the quantity to go down to
0to facilitate the "Out of Stock" state. - The "Increase" button is disabled when
quantityreachesmaxQty.
- The "Decrease" button allows the quantity to go down to
-
Enhancing the "Add to Cart" Button:
disabled={!selectedSize && product.has_size || !selectedColor && product.has_color || maxQty === 0}- The "Add to Cart" button is disabled if:
- A required option (size or color) isn't selected.
maxQtyis0, indicating that the selected combination is out of stock.
- Adjusted the styling to reflect the disabled state appropriately.
- The "Add to Cart" button is disabled if:
-
Handling Cart Item with Both Size and Color:
const cartItem = { product_id: product.id, size_id: selectedSize ? selectedSize.id : null, color_id: selectedColor ? selectedColor.id : null, qty: quantity, price: selectedSize ? selectedSize.price : product.price, };- Included both
size_idandcolor_idin thecartItemto ensure that the correct variant is managed in the cart.
existingItemIndex = cart.findIndex( (item) => item.product_id === cartItem.product_id && item.size_id === cartItem.size_id && item.color_id === cartItem.color_id );- Modified the search to include both
size_idandcolor_idwhen checking if an item exists in the cart.
- Included both
-
Default Selections:
useEffect(() => { if (product?.sizes?.length > 0) { setSelectedSize(product.sizes[0]); } else { setSelectedSize(null); } if (product?.colors?.length > 0) { setSelectedColor(product.colors[0]); } else { setSelectedColor(null); } }, [product]);- Automatically selects the first size and color (if available) when the product changes.
Assumptions & Notes
-
Product Data Structure:
- This implementation assumes that each
sizeandcolorhas its ownqtyattribute. - If the product has variants that are combinations of size and color with their own unique
qty, you'll need to adjust the logic to fetch theqtybased on both selections. This might involve restructuring your data or adding a variant lookup.
- This implementation assumes that each
-
Handling Variants:
- If your system supports variants (specific combinations of size and color), consider adding a
variantsarray in your product data, where each variant has its ownsize,color, andqty. - The
maxQtycomputation would then involve finding the variant that matches bothselectedSizeandselectedColorand using itsqty.
- If your system supports variants (specific combinations of size and color), consider adding a
-
UI/UX Considerations:
- Ensure that the "Out of Stock" message is prominent to inform users clearly.
- Consider providing tooltips or additional information if a combination is out of stock to enhance user experience.
-
Accessibility:
- Ensure that all interactive elements are keyboard accessible and have appropriate
ariaattributes for better accessibility.
- Ensure that all interactive elements are keyboard accessible and have appropriate
-
Optimizing Performance:
- The use of
useMemoanduseCallbackhooks helps in optimizing performance by memoizing computations and functions, preventing unnecessary re-renders.
- The use of
-
Error Handling:
- The implementation includes basic error handling when interacting with
localStorage. Depending on your application's requirements, you might want to enhance this further.
- The implementation includes basic error handling when interacting with
Final Thoughts
By integrating these enhancements, your
ProductModalcomponent will now effectively manage quantity restrictions based on user selections and provide clear feedback when a product variant is out of stock. Always ensure to test these changes thoroughly to handle various product configurations and edge cases. -