diff --git a/Componenets:Hierarchy.png b/Componenets:Hierarchy.png new file mode 100644 index 0000000..9069a0b Binary files /dev/null and b/Componenets:Hierarchy.png differ diff --git a/src/App.jsx b/src/App.jsx index 03e658b..946a2c0 100644 --- a/src/App.jsx +++ b/src/App.jsx @@ -1,31 +1,48 @@ import './styles/reset.css' import './styles/index.css' - -import initialStoreItems from './store-items' +import {useState} from 'react' +import initialStoreItems from './store-items' +import Header from './Header' +import MainSection from './MainSection' export default function App() { + + const [storeItems] = useState(initialStoreItems) + const[cartItems, setCartItems] = useState([]) + + + const addToCart = (targetItem) => { + const exisitingItem = cartItems.find(item => item.id === targetItem.id) + if(exisitingItem) { + const updateCart = cartItems.map(item => + item.id === targetItem.id ? {...item, quantity: item.quantity + 1 } : item + ) + setCartItems(updateCart) + } else { + setCartItems([...cartItems, targetItem]) + } + } + + const removeItem = (targetItem) => { + const exisitingItem = cartItems.find(item => item.id === targetItem.id) + if (exisitingItem.quantity > 1) { + const updateCart = cartItems.map(item => + item.id === targetItem.id ? {...item, quantity: item.quantity - 1 } : item + ) + setCartItems(updateCart) + } else { + setCartItems(cartItems.filter(item => item != targetItem)) + } + } + + const calculateTotal = () => { + return cartItems.reduce((acc, item) => acc + (item.quantity * item.price), 0).toFixed(2); + } + return ( <> -
-

Greengrocers

- -
-
-

Your Cart

-
- -
-
-
-

Total

-
-
- £0.00 -
-
-
+
+
Icons made by + +

{item.name}

+ +{item.quantity} + + +) +} \ No newline at end of file diff --git a/src/Header.jsx b/src/Header.jsx new file mode 100644 index 0000000..12a0887 --- /dev/null +++ b/src/Header.jsx @@ -0,0 +1,14 @@ +import StoreItem from './StoreItem' + +export default function Header({ storeItems, addToCart}) { + return ( +
+

Greengrocers

+
    + {storeItems.map((item) => ( + + ))} +
+
+ ) +} \ No newline at end of file diff --git a/src/MainSection.jsx b/src/MainSection.jsx new file mode 100644 index 0000000..0089901 --- /dev/null +++ b/src/MainSection.jsx @@ -0,0 +1,29 @@ +import CartItem from './CartItem' + +export default function MainSection({ cartItems, addToCart, removeItem, calculateTotal}) { + return ( +
+

Your Cart

+
+
    + {cartItems.map((item) => ( + + ))} +
+
+
+
+

Total

+
+
+ £{calculateTotal()} +
+
+
+ + ) +} + + + + diff --git a/src/StoreItem.jsx b/src/StoreItem.jsx new file mode 100644 index 0000000..f5f7c30 --- /dev/null +++ b/src/StoreItem.jsx @@ -0,0 +1,10 @@ +export default function StoreItem({ item, addToCart }) { + return ( +
  • +
    + {item.name} +
    + +
  • + ) +} \ No newline at end of file