Skip to content

Instantly share code, notes, and snippets.

@MonteLogic
Created April 20, 2023 03:42
Show Gist options
  • Save MonteLogic/a4e2d765970bf8a148fb542a3f1c850a to your computer and use it in GitHub Desktop.
Save MonteLogic/a4e2d765970bf8a148fb542a3f1c850a to your computer and use it in GitHub Desktop.
import { useEffect, useState } from '@wordpress/element';
import { select } from '@wordpress/data';
const isEditor = !!select('core/editor');
console.log(tabbedTableAttrs.product_info)
const tabbedTableInfoAttrs = tabbedTableAttrs.product_info;
const FrontTabbedComponent = () => {
const [selectedTab, setSelectedTab] = useState("allFlavors");
const [addedToCart, setAddedToCart] = useState(false);
const [addedProductName, setAddedProductName] = useState("");
if (isEditor) {
return null;
}
const handleTabClick = (tabName) => {
setSelectedTab(tabName);
};
const handleAddToCart = (productIDParam, productName) => {
const data = {
product_id: productIDParam,
quantity: 1,
};
const addToCartUrl = '/?add-to-cart=' + data.product_id + '&quantity=' + data.quantity;
fetch(addToCartUrl, {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
body: data,
}).then(() => {
setAddedToCart(true);
setAddedProductName(productName);
setTimeout(() => {
setAddedToCart(false);
setAddedProductName("");
}, 3000);
});
};
return (
<div>
{addedToCart && (
<div className="added-to-cart-banner">
<p>{addedProductName} added to cart!</p>
</div>
)}
<div className="tab-buttons">
<button
onClick={() => handleTabClick("allFlavors")}
className={selectedTab === "allFlavors" ? "active" : ""}
>
All Flavors
</button>
<button
onClick={() => handleTabClick("collections")}
className={selectedTab === "collections" ? "active" : ""}
>
Collections
</button>
</div>
{selectedTab === "allFlavors" && (
<div className="product-list">
{tabbedTableInfoAttrs.map((product) => (
<div key={product.name} className="product-item">
<img src={product.imageURL} alt={product.name} />
<div className="product-info">
<h3>{product.name}</h3>
<p>{product.price}</p>
</div>
<button onClick={() => handleAddToCart(product.productID, product.name)}>Add To Cart</button>
</div>
))}
</div>
)}
{selectedTab === "collections" && (
<div className="collection-list">
{collections.map((collection) => (
<a
key={collection.name}
href={collection.link}
className="collection-item"
>
<h3>{collection.name}</h3>
</a>
))}
</div>
)}
</div>
);
};
export default FrontTabbedComponent;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment