diff --git a/src/components/Meals/MealItem/MealItem.js b/src/components/Meals/MealItem/MealItem.js index 060c813..6c3773a 100644 --- a/src/components/Meals/MealItem/MealItem.js +++ b/src/components/Meals/MealItem/MealItem.js @@ -1,9 +1,22 @@ +import { useContext } from "react"; import classes from "./MealItem.module.css"; import MealItemForm from "./MealItemForm"; +import CartContext from "../../../store/cart-context"; const MealItem = (props) => { 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 (
  • @@ -12,7 +25,7 @@ const MealItem = (props) => {
    {price}
    - +
  • ); diff --git a/src/components/Meals/MealItem/MealItemForm.js b/src/components/Meals/MealItem/MealItemForm.js index 4187312..b8254c5 100644 --- a/src/components/Meals/MealItem/MealItemForm.js +++ b/src/components/Meals/MealItem/MealItemForm.js @@ -1,10 +1,33 @@ import classes from "./MealItemForm.module.css"; import Input from "../../UI/Input"; +import { useRef, useState } from "react"; 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 ( -
    + { }} /> + {!amountIsValid &&

    Please enter a valid amount (1-5).

    }
    ); }; diff --git a/src/components/UI/Input.js b/src/components/UI/Input.js index 93aaba5..88bac99 100644 --- a/src/components/UI/Input.js +++ b/src/components/UI/Input.js @@ -1,12 +1,13 @@ +import React from "react"; import classes from "./Input.module.css"; -const Input = (props) => { +const Input = React.forwardRef((props, ref) => { return (
    - +
    ); -}; +}); export default Input;