ProductCard.jsx에
useContext를 사용해서 userContext를 가져온다.
userContext에는 현재 로그인 중인 유저의 정보가 담겨있고
const ProductCard = ({ product }) => {
const { addToCart } = useContext(CartContext);
const user = useContext(UserContext);
장바구니 버튼에 조건을 추가하여 유저가 있을 경우에만 노출하게 한다.
{/* 재고가 있을 경우 및 유저가 있을 경우에만 장바구니 담기 표시 */}
{product?.stock > 0 && user && (
<button
className="add_to_cart"
onClick={() => addToCart(product, 1)}
>
<img src={basket} alt="basket button" />
</button>
)}
</footer>
1. 유저 없을 경우
2. 유저 있을 경우
마찬가지로 SingleProductPage.jsx에도
컨텍스트로 user를 가져온다
const { addToCart } = useContext(CartContext);
const user = useContext(UserContext);
구매개수 버튼과 장바구니 추가 버튼은 유저가 있을경우에만 노출
{user && (
<>
<h2 className="quantity_title">구매개수:</h2>
<div className="align_center quantity_input">
<QuantityInput
quantity={quantity}
setQuantity={setQuantity}
stock={product.stock}
/>
</div>
<button
onClick={() => addToCart(product, quantity)}
className="search_button add_cart"
>
장바구니 추가
</button>
</>
)}
</div>
</>
)}
</section>
);
};
1. 유저가 없을 경우
2. 유저가 있을 경우
'FRONTEND > React' 카테고리의 다른 글
[myCart] 네비게이션 가드(로그인 유저가 아니면 url주소로 접근 불가) 설정 (0) | 2023.12.22 |
---|---|
[myCart] 주문하기 (checkout) 및 주문 페이지에서 백엔드(orders) 데이터 가져오기 (0) | 2023.12.22 |
[myCart] ProductCard 에서 바로 장바구니 담기 (0) | 2023.12.21 |
[myCart] 장바구니 구매수량 변경 및 백엔드 업데이트 (0) | 2023.12.21 |
[myCart] 장바구니 상품 삭제 (0) | 2023.12.21 |