Cmarket Hooks 과제 정리
import React, { useState } from "react";
import Nav from "./components/Nav";
import ItemListContainer from "./pages/ItemListContainer";
import "./App.css";
import "./variables.css";
import { BrowserRouter as Router, Routes, Route } from "react-router-dom";
import ShoppingCart from "./pages/ShoppingCart";
import { initialState } from "./assets/state";
function App() {
const [items, setItems] = useState(initialState.items);
const [cartItems, setCartItems] = useState(initialState.cartItems);
const addToCart = (items) => {
// 카트리스트에 내가 넣을 물품이 존재하는지 확인하고
// 존재한다면 A에 quantity만 올려주고 만약 존재하지 않으면 새로 만든다. <- 마지막 작업
// 혹은 filter문을 사용해서 존재여부를 걸러내준 다음에 있으면 quantity +1 없으면 else문 처럼 작성
console.log(cartItems);
let newCartItem = [...cartItems];
const found = cartItems.filter((el) => el.itemId === items); // 3번을 인자로 넣으면 3번의 값의 데이터만 남아있음
if (found.length > 0) {
newCartItem.map((el) => {
if (el.itemId === items) {
el.quantity = el.quantity + 1;
}
});
setCartItems(newCartItem);
// 같은 Id의 pu의 값을 올려줘야한다
} else {
setCartItems([...cartItems, { itemId: items, quantity: 1 }]);
}
};
const DeleteToCart = (itemId) => {
setCartItems(cartItems.filter((el) => el.itemId !== itemId));
};
return (
<Router>
<Nav />
<Routes>
<Route
path="/"
element={<ItemListContainer items={items} addToCart={addToCart} />}
/>
<Route
path="/shoppingcart"
element={
<ShoppingCart
cartItems={cartItems}
items={items}
DeleteToCart={DeleteToCart}
/>
}
/>
</Routes>
<img
id="logo_foot"
src={`${process.env.PUBLIC_URL}/codestates-logo.png`}
alt="logo_foot"
/>
</Router>
);
}
export default App;
// nav.js : App.js의 자식 컴포넌트 페이지 네이게이션 담당
// CartItem.js : ShoppingCart.js의 자식 컴포넌트 상품을 나타냄
// Item.js : ShoppingCart.js의 자식 컴포넌트 장바구니 표시
// OrderSummary.js : ShoppingCart.js의 자식 컴포넌트 상품을 표시해줌
// Router, Route, Switch
// App.js에서 함수 만들고 자식에게 넘겨주기
// 장바구니담기를 누른만큼 갯수가 늘어나야함 - 장바구니안에 들어있는지 확인후 true면 quantity +1 해주고 아니면 새로 들이기
// 장바구니 페이지에서 아이템갯수 변경가능 해야함
// 메인페이지에서 장바구니(0) 의 갯수가 늘어나야함
import React from "react";
import Item from "../components/Item";
function ItemListContainer({ items, addToCart }) {
return (
<div id="item-list-container">
<div id="item-list-body">
<div id="item-list-title">쓸모없는 선물 모음</div>
{items.map((item, idx) => (
<Item item={item} key={idx} handleClick={() => addToCart(item.id)} />
))}
</div>
</div>
);
}
export default ItemListContainer;
import React, { useState } from "react";
import CartItem from "../components/CartItem";
import OrderSummary from "../components/OrderSummary";
export default function ShoppingCart({ items, cartItems, DeleteToCart, UpdateToCart }) {
const [checkedItems, setCheckedItems] = useState(
cartItems.map((el) => el.itemId)
);
const handleCheckChange = (checked, id) => {
if (checked) {
setCheckedItems([...checkedItems, id]);
} else {
setCheckedItems(checkedItems.filter((el) => el !== id));
}
};
const handleAllCheck = (checked) => {
if (checked) {
setCheckedItems(cartItems.map((el) => el.itemId));
} else {
setCheckedItems([]);
}
};
const handleQuantityChange = (quantity, itemId) => {
};
const handleDelete = (itemId) => {
setCheckedItems(checkedItems.filter((el) => el !== itemId));
DeleteToCart(itemId);
};
const getTotal = () => {
let cartIdArr = cartItems.map((el) => el.itemId);
let total = {
price: 0,
quantity: 0,
};
for (let i = 0; i < cartIdArr.length; i++) {
if (checkedItems.indexOf(cartIdArr[i]) > -1) {
let quantity = cartItems[i].quantity;
let price = items.filter((el) => el.id === cartItems[i].itemId)[0]
.price;
total.price = total.price + quantity * price;
total.quantity = total.quantity + quantity;
}
}
return total;
};
const renderItems = items.filter(
(el) => cartItems.map((el) => el.itemId).indexOf(el.id) > -1
);
const total = getTotal();
return (
<div id="item-list-container">
<div id="item-list-body">
<div id="item-list-title">장바구니</div>
<span id="shopping-cart-select-all">
<input
type="checkbox"
checked={checkedItems.length === cartItems.length ? true : false}
onChange={(e) => handleAllCheck(e.target.checked)}
></input>
<label>전체선택</label>
</span>
<div id="shopping-cart-container">
{!cartItems.length ? (
<div id="item-list-text">장바구니에 아이템이 없습니다.</div>
) : (
<div id="cart-item-list">
{renderItems.map((item, idx) => {
const quantity = cartItems.filter(
(el) => el.itemId === item.id
)[0].quantity;
return (
<CartItem
key={idx}
handleCheckChange={handleCheckChange}
handleQuantityChange={handleQuantityChange}
handleDelete={handleDelete}
item={item}
checkedItems={checkedItems}
quantity={quantity}
/>
);
})}
</div>
)}
<OrderSummary total={total.price} totalQty={total.quantity} />
</div>
</div>
</div>
);
}