JSFiddle - React, Tailwind, and code Playground
HTML
<table id = "shoppingcart">
</table>
JavaScript
class ShoppingCart
{
constructor()
{
this.$shoppingCart = $('#shoppingcart');
// Cartitems is an independent array from UI,
// but UI is updated when items are added here
this.cartItems = [];
}
addItem(name, price)
{
// Add item to the cartItems array
this.cartItems.push({ name: name, price: price });
// Update UI
this.render();
}
render()
{
let appendString = '';
// Clear the shopping cart table UI element
this.$shoppingCart.empty();
// Go through the cartItems-array and make the appropriate table rows
this.cartItems.forEach(item =>
{
appendString += `<tr><td>${item.name}</td><td>${item.price}</td></tr>`;
});
// Update the table with new rows
this.$shoppingCart.append(appendString);
}
}
const cart = new ShoppingCart();
// Don't have to worry about updating the UI when you add an item
cart.addItem('Banana', 10);
cart.addItem('Apple', 3);
cart.addItem('Beer', 12);