diff --git a/src/components/main/QuantityInput.tsx b/src/components/main/QuantityInput.tsx index 05d592810..a3efea5ea 100644 --- a/src/components/main/QuantityInput.tsx +++ b/src/components/main/QuantityInput.tsx @@ -1,6 +1,7 @@ -import { WheelEventHandler, ChangeEventHandler, KeyboardEventHandler } from 'react'; +import { WheelEventHandler, ChangeEventHandler, FormEventHandler, FormEvent } from 'react'; import { FaCaretUp, FaCaretDown } from 'react-icons/fa'; import { css, styled } from 'styled-components'; +import { NOT_NUMBER } from '../../constants'; import Input from '../common/Input'; interface Props { @@ -14,8 +15,14 @@ const QuantityInput = ({ id, value, onChange }: Props) => { currentTarget.blur(); }; - const handleDotPrevent: KeyboardEventHandler = (event) => { - if (event.key === '.') event.preventDefault(); + const handleDigitsOnlyAllow: FormEventHandler = ({ + currentTarget, + }: FormEvent) => { + const input = currentTarget; + const newValue = input.value.replace(NOT_NUMBER, ''); + + input.value = ''; + input.value = newValue; }; return ( @@ -34,7 +41,7 @@ const QuantityInput = ({ id, value, onChange }: Props) => { css={QuantityInputStyle} onWheel={handleScrollPrevent} onChange={onChange} - onKeyDown={handleDotPrevent} + onInput={handleDigitsOnlyAllow} /> diff --git a/src/hooks/useCart.ts b/src/hooks/useCart.ts index a13149876..cdaab1a47 100644 --- a/src/hooks/useCart.ts +++ b/src/hooks/useCart.ts @@ -36,7 +36,7 @@ export const useSetCart = (id: number) => { setCart((prev: CartItem[]) => { const { cart, cartItemIndex, alreadyHasCartItem } = findCartItemIndex(prev); - if (Number.isNaN(Number(value))) return removeProduct(cart, cartItemIndex); + if (value === '') return removeProduct(cart, cartItemIndex); if (alreadyHasCartItem) { const updatedItem = { ...prev[cartItemIndex], quantity: Number(value) }; diff --git a/src/hooks/useHandleQuantityInput.ts b/src/hooks/useHandleQuantityInput.ts index bfa0b917a..d741e3fbc 100644 --- a/src/hooks/useHandleQuantityInput.ts +++ b/src/hooks/useHandleQuantityInput.ts @@ -1,5 +1,5 @@ import { ChangeEventHandler, Dispatch, SetStateAction } from 'react'; -import { MAX_NUMBER_LENGTH, NOT_NUMBER, QUANTITY } from '../constants'; +import { MAX_NUMBER_LENGTH, QUANTITY } from '../constants'; interface Props { setIsSelected: (value: SetStateAction) => void; @@ -21,9 +21,9 @@ export const useHandleQuantityInput = ({ ...props }: Props) => { return setQuantity(QUANTITY.INITIAL); } - const onlyTwoDigits = parseInt(value.replace(NOT_NUMBER, '').slice(0, MAX_NUMBER_LENGTH)); + const onlyTwoDigits = value.slice(0, MAX_NUMBER_LENGTH); setQuantity(onlyTwoDigits); - addToCart(String(onlyTwoDigits)); + addToCart(onlyTwoDigits); }; return handleNumberInputChange;