728x90
cart-context.js
import { createContext } from "react";
export const CartContext = createContext("");
App
import { useState } from "react"
import CartModel from "./components/CartModel"
import {CartContext} from"./store/cart-context"
export default function App(){
const [shoppingCart, setShoppingCart] = useState([]);
function handleAddItemToCart(cart){
console.log(cart);
setShoppingCart([...shoppingCart, cart]);
}
return (
<>
<h1>App</h1>
<CartContext.Provider value={shoppingCart}>
<CartModel onAddToCart = {handleAddItemToCart}></CartModel>
</CartContext.Provider>
</>
)
}
CartModel
import { useRef } from "react"
import Cart from "./Cart"
export default function CartModel({onAddToCart}){
const cart = useRef();
return (
<div>
cart: <input ref={cart}></input>
<button onClick={() => onAddToCart(cart.current.value)} >Add to Cart</button>
<hr></hr>
<Cart></Cart>
</div>
)
}
Cart
import { useContext } from "react"
import { CartContext } from "../store/cart-context"
export default function Cart(){
const items = useContext(CartContext);
console.log("cart items: ", items);
return (
<ul>
{items.map((row, idx) => {
return(
<li key={idx}>
{row}
</li>
)
})}
</ul>
)
}
'단순 코드 기록 > React' 카테고리의 다른 글
React_useReducer_숫자 증감 (0) | 2024.03.18 |
---|---|
React_useContext로 변수와 함수 전송 (0) | 2024.03.18 |
React_useContext Hook (0) | 2024.03.18 |
React_부모창에서 자식창의 함수 불러오기 (0) | 2024.03.18 |
React_속성으로 함수 사용 (0) | 2024.03.18 |