Listing 4-4: Putting everything in one component
Cart
total: $5
import React,{useState} from 'react';
import styles from './Cart.css.js';
function Cart(props){
const [inCart,setInCart] = useState(props.inCart);
const removeFromCart = (item)=>{
const index = inCart.indexOf(item);
const newCart = [...inCart.slice(0, index), ...inCart.slice(index + 1)];
setInCart(newCart);
};
const calculatedTotal = inCart.reduce((accumulator, item) => accumulator + (item.price || 0), 0);
let ItemList = inCart.map((item)=>{
return (<div key={item.id}>{item.title} - {item.price}
<button onClick={()=>{removeFromCart(item)}}>remove</button></div>)
});
return(
<div style={styles.cart}>
<h2>Cart</h2>
{ItemList}
<p>total: 5</p>
<button>Checkout</button>
</div>
);
}
Cart.defaultProps = {
inCart: [{id:1,title:"React JS Foundations",price:5}]
};
export default Cart;
Download the examples, report issues, and ask/answer questions in the discussion area by visiting the book's github page. All of the code for the book is also available on codesandbox.io for you to play around with.
ReactJS Foundations is published by John Wiley and Sons, Inc and is available in paperback and eBook.