JSFiddle - React, Tailwind, and code Playground
HTML
<script src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<div id="app"></div>
CSS
* {
font-family: monospace;
}
Babel + JSX
const ProductsList = ({ title, items, itemText, buttonText, onClick }) =>
<div>
<h3>{title}</h3>
<ul>{items.map(n => (
<li key={n.id}>
<button onClick={() => onClick(n)}>{buttonText}</button>
{itemText(n)}
</li>))}
</ul>
</div>;
const Cart = ({ products, remove }) =>
<div>
<ProductsList
title="cart"
items={products}
itemText={n => `${n.name} | $${n.price} * ${n.qty} = $${n.price * n.qty}`}
buttonText="del"
onClick={remove}
/>
<div>TOTAL: ${products.reduce((acc, n) => acc + n.price * n.qty, 0)}</div>
</div>;
function App({ products }) {
const [ cart, setCart ] = React.useState([]);
const addToCart = product =>
setCart(cart => cart.some(n => n.id === product.id)
? cart.map(n => n.id === product.id ? { ...n, qty: n.qty + 1 } : n)
: [ ...cart, { ...product, qty: 1 } ]
);
const removeFromCart = ({ id }) =>
setCart(cart => cart.filter(n => n.id !== id));
return (
<div>
<ProductsList
title="products"
items={products}
itemText={n => `${n.name} | $${n.price}`}
buttonText="add to cart"
onClick={addToCart}
/>
<hr/>
<Cart products={cart} remove={removeFromCart} />
</div>
);
}
ReactDOM.render(
<App
products={[
{ id: 1, name: 'xxx', price: 1 },
{ id: 2, name: 'yyy', price: 10 },
{ id: 3, name: 'zzz', price: 100 },
]}
/>,
document.getElementById('app')
);