Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
51 changes: 48 additions & 3 deletions apps/what-today/src/components/experiences/PriceInput.tsx
Original file line number Diff line number Diff line change
@@ -1,14 +1,59 @@
import { Input } from '@what-today/design-system';
import { memo } from 'react';
import { type ChangeEvent, memo, useEffect, useState } from 'react';

import type InputProps from '@/types/InputProps';

function PriceInput({ error, ...props }: InputProps) {
export interface PriceInputProps extends InputProps {
value: number;
onChange: (value: number) => void;
}

function PriceInput({ value, onChange, error }: PriceInputProps) {
const formatNumber = (num: number | string) => num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',');
const unformatNumber = (str: string) => str.replaceAll(',', '');

const [display, setDisplay] = useState('');

useEffect(() => {
if (typeof value === 'number' && !isNaN(value)) {
setDisplay(formatNumber(value));
} else {
setDisplay('');
}
}, [value]);

const handleChange = (e: ChangeEvent<HTMLInputElement>) => {
const raw = unformatNumber(e.target.value);
const numeric = Number(raw);

if (!isNaN(numeric)) {
setDisplay(formatNumber(numeric));
onChange(numeric); // 외부에는 숫자로 전달
} else {
setDisplay('');
onChange(0);
}
};

const handleBlur = () => {
const numeric = Number(unformatNumber(display));
if (!isNaN(numeric)) {
setDisplay(formatNumber(numeric));
}
};

return (
<Input.Root className='w-full' error={error}>
<Input.Label>가격</Input.Label>
<Input.Wrapper>
<Input.Field min={0} {...props} placeholder='가격을 입력해주세요' type='number' />
<Input.Field
inputMode='numeric'
placeholder='가격을 입력해주세요'
type='text'
value={display}
onBlur={handleBlur}
onChange={handleChange}
/>
</Input.Wrapper>
<Input.ErrorMessage />
</Input.Root>
Expand Down
11 changes: 6 additions & 5 deletions apps/what-today/src/pages/experiences/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -291,11 +291,12 @@ export default function CreateExperience() {

<DescriptionTextarea {...register('description')} error={errors.description?.message} />

<PriceInput
{...register('price', {
valueAsNumber: true,
})}
error={errors.price?.message}
<Controller
control={control}
name='price'
render={({ field }) => (
<PriceInput error={errors.price?.message} value={field.value} onChange={field.onChange} />
)}
/>

<Controller
Expand Down