728x90
배운 것, 공부한 것, 메모할 것
1. React
- 데모 프로젝트 복습 및 재구현
- Context API, reducer 중심

Add 버튼을 누르면 상단 숫자가 추가되는 논리
1. MealItemForm.js에서 Add 버튼을 눌렀을 때 onSubmitHandler 함수를 실행하여 유효성 검증을 한 뒤 총 amount를 계산하고 이를 props.onAddCart로 상위 컴포넌트로 전달한다. (하단의 props.onAddCart)
MealItemForm.js
const submitHandler = (e) => {
e.preventDefault();
const enteredAmount = amountInputRef.current.value;
const enteredAmountNumber = +enteredAmount;
if (
enteredAmount.trim().length === 0 ||
enteredAmount < 1 ||
enteredAmount > 5
) {
setIsAmountValid(false);
return;
}
props.onAddToCart(enteredAmountNumber);
};
return (
<form onSubmit={submitHandler} className={classes.form}>
<Input
ref={amountInputRef}
label="Amount"
input={{
type: "number",
max: "5",
min: "1",
defaultValue: "1",
}}
/>
<button>+ Add</button>
{!isAmountValid && <p>1~5 사이의 갯수를 입력해주세요.</p>}
</form>
);
};
2. MealItem.js에서 <MealItemForm onAddCart={addToCartHandler} />를 통해 1.에서 전달받은 값을 addToCartHandler 함수 실행 시 반영한다.
MealItem.js
import React, { Fragment, useContext } from "react";
import classes from "./MealItem.module.css";
import MealItemForm from "./MealItemForm";
import CartContext from "store/cart-context";
const MealItem = (props) => {
const cartCtx = useContext(CartContext);
const price = `$${props.price.toFixed(2)}`;
const addToCartHandler = (amount) => {
cartCtx.addItem({
id: props.id,
name: props.name,
amount: amount,
price: props.price,
});
};
return (
<Fragment>
<li className={classes.meal}>
<div>
<h3>{props.name}</h3>
<div className={classes.description}>{props.description}</div>
<span className={classes.price}>{price}</span>
</div>
<div>
<MealItemForm onAddToCart={addToCartHandler} />
</div>
</li>
</Fragment>
);
};
export default MealItem;
(작성중)
'today i learned' 카테고리의 다른 글
| today i learned 1/9 (0) | 2022.01.09 |
|---|---|
| today i learned 1/8 (0) | 2022.01.09 |
| today i learned 1/6 (0) | 2022.01.06 |
| today i learned 1/5 (0) | 2022.01.05 |
| today i learned 1/4 (0) | 2022.01.04 |