JSFiddle - React, Tailwind, and code Playground
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div id="productsContainer">
<div id="total">
<!-- The total will be shown here -->
</div>
</div>
<script src="script.js"></script>
</body>
</html>
CSS
#productsContainer {
display: flex;
flex-direction: column;
flex-wrap: wrap;
margin-top: 20px;
position: relative;
}
.product {
width: 200px;
margin: 10px;
padding: 10px;
border: 1px solid #ccc;
border-radius: 5px;
text-align: center;
}
#total {
position: absolute;
font-size: 20px;
font-weight: bold;
bottom: -20px;
left: 10px;
background-color: #ececec;
}
@media (min-width: 768px) {
#productsContainer {
flex-direction: row;
}
}
JavaScript
class Cart {
constructor(products, currency) {
this.products = [];
this.currency = "";
}
initializeQuantity = () => {
for (let product of this.products) {
product.quantity = 0; // Initialize quantity to 0 for each product
}
console.log(this.products.quantity);
};
updateUnits = (sku, units) => {
// Update the number of units to be purchased for a product
let product = this.products.find((p) => p.sku === sku);
if (product) {
product.quantity = units;
console.log(this.products.quantity);
} else {
this.products.push({ sku: sku, quantity: units });
}
};
getProductInformation = (sku) => {
// Returns the data of a product along with the selected units
// For example:
// {
// "sku": "0K3QOSOV4V",
// "quantity": 3
// }
return this.products.find((p) => p.SKU === sku);
};
getAllProducts = () => {
return this.products;
};
getCart = () => {
// Returns information about the products added to the cart
// Along with the calculated total of all products
// For example:
// {
// "total": "5820",
// "currency: "€",
// "products" : [
// {
// "sku": "0K3QOSOV4V"
// ..
// }
// ]}
let total = this.products.reduce(
(sum, p) => sum + p.quantity * p.price,
0
);
return { total: total, currency: this.currency, products: this.products };
};
}
let cart = new Cart();
cart.initializeQuantity();
const getProductsData = async () => {
let response = await fetch(
"https://jsonblob.com/api/jsonBlob/1241305513466912768"
);
let data = await response.json();
console.log(data);
return data; // return the full response
};
const showProducts = (products) => {
/* console.log(products) */;
...