Skip to content

Commit 63d566d

Browse files
feat: add inCents for field number
1 parent a9a9df8 commit 63d566d

File tree

3 files changed

+19
-2
lines changed

3 files changed

+19
-2
lines changed

app/components/form/field-number/docs.stories.tsx

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -98,6 +98,7 @@ export const Currency = () => {
9898
style: 'currency',
9999
currency: 'EUR',
100100
}}
101+
inCents
101102
/>
102103
<FormFieldHelper>Help</FormFieldHelper>
103104
</FormField>

app/components/form/field-number/index.tsx

Lines changed: 17 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import {
55
FieldPath,
66
FieldValues,
77
} from 'react-hook-form';
8+
import { isNullish } from 'remeda';
89

910
import { cn } from '@/lib/tailwind/utils';
1011

@@ -20,6 +21,7 @@ export type FieldNumberProps<
2021
> = FieldCommonProps<TFieldValues, TName> & {
2122
type: 'number';
2223
containerProps?: ComponentProps<'div'>;
24+
inCents?: boolean;
2325
} & RemoveFromType<
2426
Omit<
2527
ComponentProps<typeof NumberInput>,
@@ -42,11 +44,23 @@ export const FieldNumber = <
4244
shouldUnregister,
4345
control,
4446
containerProps,
47+
inCents,
4548
...rest
4649
} = props;
4750

4851
const ctx = useFormField();
4952

53+
const formatValue = (
54+
value: number | undefined | null,
55+
type: 'to-cents' | 'from-cents'
56+
) => {
57+
if (isNullish(value)) return null;
58+
if (inCents !== true) return value ?? null;
59+
if (type === 'to-cents') return Math.round(value * 100);
60+
if (type === 'from-cents') return value / 100;
61+
return null;
62+
};
63+
5064
return (
5165
<Controller
5266
name={name}
@@ -55,7 +69,7 @@ export const FieldNumber = <
5569
defaultValue={defaultValue}
5670
shouldUnregister={shouldUnregister}
5771
render={({ field, fieldState }) => {
58-
const { onChange, ...fieldProps } = field;
72+
const { onChange, value, ...fieldProps } = field;
5973
return (
6074
<div
6175
{...containerProps}
@@ -74,8 +88,9 @@ export const FieldNumber = <
7488
}
7589
{...rest}
7690
{...fieldProps}
91+
value={formatValue(value, 'from-cents')}
7792
onValueChange={(value) => {
78-
onChange(value);
93+
onChange(formatValue(value, 'to-cents'));
7994
}}
8095
/>
8196
<FormFieldError />

app/components/ui/number-input.tsx

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ type NumberInputProps = ComponentProps<typeof NumberField.Root> &
1515
InputPropsRoot & {
1616
inputProps?: Omit<RemoveFromType<InputProps, InputPropsRoot>, 'endElement'>;
1717
buttons?: 'classic' | 'mobile';
18+
inCents?: boolean;
1819
};
1920

2021
export const NumberInput = ({

0 commit comments

Comments
 (0)