일단 html, css로 유사하게 만든다.
<Link to="/cart">
<button type="button" onClick={()=>increaseQuantity(id)}>
장바구니에 담기
</button>
</Link>
장바구니를 누르면 cart페이지로 이동하고 수량 증가
context.tsx
import { createContext, useContext, ReactNode, useState } from "react";
type CartItem = {
id: number;
name: string;
quantity: number;
};
type ShoppingCartContext = {
increaseQuantity: (id: number) => void
};
type ShoppingCartProvider = {
children: ReactNode;
};
export const CartContext = createContext({} as ShoppingCartContext);
export const useShoppingCart = () => {
return useContext(CartContext);
};
export const ShoppingCartProvider = ({ children }: ShoppingCartProvider) => {
const [items, setItems] = useState<CartItem[]>([]);
const increaseQuantity = (id: number) => {
return setItems((currItems) : any => {
if (currItems.find((item) => item.id === id) == null) {
return [...currItems, { id, quantity: 1 }];
} else {
return currItems.map((item) => {
if (item.id === id) {
return { ...item, quantity: item.quantity + 1 };
} else {
return item;
}
});
}
});
};
return (
<CartContext.Provider value={{ increaseQuantity }}>
{children}
</CartContext.Provider>
);
};
import { useShoppingCart } from "../context/CartContext";
import datas from "../data/item.json";
type CartItemProps = {
id: number;
quantity: number;
};
const CartItem = ({ id, quantity }: CartItemProps) => {
const { formatCurrency } = useShoppingCart()
const item = datas.find((i) => i.id === id);
if (item == null) return null;
return (
<li>
<h1>{formatCurrency(item.price)}</h1>
</li>
);
};
export default CartItem;
가격을 가져온다
const CURRENCY_FORMATTER = new Intl.NumberFormat(undefined, {
currency: "KRW",
style: "currency",
});
const formatCurrency = (number: number) => {
return CURRENCY_FORMATTER.format(number);
};
{formatCurrency(items.reduce((total, item)=>{
const data = datas.find(i=>i.id === item.id)
return total + (data?.price || 0) * item.quantity
},0))}
장바구니 안에 들어온 총 개수 * 가격을 가져온다