add item to cart by cart context

This commit is contained in:
oscar 2023-03-18 22:16:10 +13:00
parent aa91bcea73
commit cae3ccc644
3 changed files with 43 additions and 5 deletions

View File

@ -1,9 +1,22 @@
import { useContext } from "react";
import classes from "./MealItem.module.css"; import classes from "./MealItem.module.css";
import MealItemForm from "./MealItemForm"; import MealItemForm from "./MealItemForm";
import CartContext from "../../../store/cart-context";
const MealItem = (props) => { const MealItem = (props) => {
const price = `$${props.price.toFixed(2)}`; const price = `$${props.price.toFixed(2)}`;
const cartCtx = useContext(CartContext);
const addToCartHandler = (amount) => {
cartCtx.addItem({
id: props.id,
name: props.name,
amount: amount,
price: props.price,
});
};
return ( return (
<li className={classes.meal}> <li className={classes.meal}>
<div> <div>
@ -12,7 +25,7 @@ const MealItem = (props) => {
<div className={classes.price}>{price}</div> <div className={classes.price}>{price}</div>
</div> </div>
<div> <div>
<MealItemForm id={props.id} /> <MealItemForm id={props.id} onAddToCart={addToCartHandler} />
</div> </div>
</li> </li>
); );

View File

@ -1,10 +1,33 @@
import classes from "./MealItemForm.module.css"; import classes from "./MealItemForm.module.css";
import Input from "../../UI/Input"; import Input from "../../UI/Input";
import { useRef, useState } from "react";
const MealItemForm = (props) => { const MealItemForm = (props) => {
const amountInputRef = useRef();
const [amountIsValid, setAmountIsValid] = useState(true);
const submitHandler = (event) => {
event.preventDefault();
const enteredAmount = amountInputRef.current.value;
const enteredAmountNumber = +enteredAmount;
if (
enteredAmount.trim().length === 0 ||
enteredAmountNumber < 1 ||
enteredAmountNumber > 5
) {
setAmountIsValid(false);
return;
}
props.onAddToCart(enteredAmountNumber);
};
return ( return (
<form className={classes.form}> <form className={classes.form} onSubmit={submitHandler}>
<Input <Input
ref={amountInputRef}
label="Amount" label="Amount"
input={{ input={{
id: "amount_" + props.id, id: "amount_" + props.id,
@ -16,6 +39,7 @@ const MealItemForm = (props) => {
}} }}
/> />
<button>+ Add</button> <button>+ Add</button>
{!amountIsValid && <p>Please enter a valid amount (1-5).</p>}
</form> </form>
); );
}; };

View File

@ -1,12 +1,13 @@
import React from "react";
import classes from "./Input.module.css"; import classes from "./Input.module.css";
const Input = (props) => { const Input = React.forwardRef((props, ref) => {
return ( return (
<div className={classes.input}> <div className={classes.input}>
<label htmlFor={props.input.id}>{props.label}</label> <label htmlFor={props.input.id}>{props.label}</label>
<input id={props.input.id} {...props.input} /> <input ref={ref} id={props.input.id} {...props.input} />
</div> </div>
); );
}; });
export default Input; export default Input;