Reputation: 85
I'm new to react and followed this tutorial to built a shopping cart. The code is pretty simple and straight forward but I would like for it to display the total price of products. How would I implement that within this code?
Here's the code. I've later separated these into 3 files, "Products", "Cart" and "Productspage" but displayed it here all together so it would simpler to see it.
import React, {useState} from 'react'
import './ProductsPage.css'
const PAGE_PRODUCTS = 'products';
const PAGE_CART = 'cart';
function ProductsPage() {
const [cart, setCart] = useState ([]);
const [page, setPage] = useState (PAGE_PRODUCTS);
const [products] = useState ([
{
name: 'Breakfast box ',
cost:'9.99$',
image: 'https://images.unsplash.com/photo-1578863950596-a74dfe8267b5?ixlib=rb-1.2.1&auto=format&fit=crop&w=1573&q=80',
},
{
name: 'Breakfast box ',
cost:'8.99$',
image: 'https://images.unsplash.com/photo-1557686652-6731ba12410f?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=634&q=80',
},
])
const addToCart = (product) => {
setCart ([...cart, {...product}])
}
const removeFromCart = (productToRemove) => {
setCart(cart.filter(product => product !== productToRemove))
}
const navigateTo = (nextPage) => {
setPage(nextPage);
};
const renderProducts = () => (
<>
<h1>Products</h1>
<div className="products">
{products.map((product , index) => (
<div className="product" key={index}>
<h3>{product.name}</h3>
<h4>{product.cost}</h4>
<img src={product.image} alt={product.name}/>
<button onClick={() => addToCart(product)}>
Add to Cart
</button>
</div>
))}
</div>
</>
);
const renderCart = () => (
<>
<h1>Cart</h1>
<div className="products">
{cart.map((product , index) => (
<div className="product" key={index}>
<h3>{product.name}</h3>
<h4>{product.cost}</h4>
<img src={product.image} alt={product.name}/>
<button onClick={() => removeFromCart(product)}>
Remove
</button>
</div>
))}
</div>
</>
)
return (
<div className="productspage">
<header>
<button onClick={()=> navigateTo(PAGE_CART)}>
Go to Cart ({cart.length})
</button>
<button onClick={()=> navigateTo(PAGE_PRODUCTS)}>
View Products
</button>
</header>
{page === PAGE_PRODUCTS && renderProducts()}
{page === PAGE_CART && renderCart()}
</div>
);
};
export default ProductsPage;
Upvotes: 0
Views: 5516
Reputation: 572
you could simply loop through array created from object, and then convert string cost to numeric (by replacing $ to nothing and cast cart to numeric with + before that) and then sum up all of them like here:
Object.keys(cart).reduce(
(prevVal, currentVal) =>
prevVal + +cart[currentVal].cost.replace("$", ""),
0
)
Upvotes: 1
Reputation: 2442
Call this function with your products list wherever you want the total cost to appear.
const getTotalCost = (productList) => {
return productList.reduce((totalCost, { cost: itemCost }) => totalCost + parseFloat(itemCost), 0);
};
This is just a regular JavaScript function that iterates the list of products and sums the cost
key and returns it.
It's not accessing any props or state so can sit outside of your component body.
Upvotes: 0
Reputation: 996
Check it out i have added js code with comments to understand easily:
`const [total,setTotal]=useState(0)` //make a new state variable
const cart =[
{
name: 'Breakfast box ',
cost:'9.99$',
image: 'https://images.unsplash.com/photo-1578863950596-a74dfe8267b5?ixlib=rb-1.2.1&auto=format&fit=crop&w=1573&q=80',
},
{
name: 'Breakfast box ',
cost:'8.99$',
image: 'https://images.unsplash.com/photo-1557686652-6731ba12410f?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=634&q=80',
},
]
//modified addToCart
const addToCart = (product) => {
const products = [...cart, product]
console.log(products)
const totalPrice = products.reduce((acc, curr)=>{ //calculate total
let cur =curr.cost.match(/\d./g).join('') //parse string to integer(cost)
return acc + Number(cur);
}, 0)
console.log("total:", totalPrice);
// setCart (products);
//setTotal(totalPrice);
}
//end addToCart
const newProduct = {
name: 'Breakfast box ',
cost:'7.99$',
image: 'https://images.unsplash.com/photo-1557686652-6731ba12410fixlib=rb1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=63',
}
addToCart(newProduct)
Upvotes: 0