Skip to content

Commit 385cfba

Browse files
committed
hotfix: make sur the number input update value on enter
1 parent c7e4e6c commit 385cfba

File tree

2 files changed

+28
-3
lines changed

2 files changed

+28
-3
lines changed

app/components/ui/number-input.stories.tsx

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -137,3 +137,13 @@ export const ShowButtons = () => {
137137
</div>
138138
);
139139
};
140+
141+
export const Controlled = () => {
142+
const [value, setValue] = useState<number | null>(10);
143+
return (
144+
<div>
145+
<NumberInput value={value} onValueChange={(v) => setValue(v)} />
146+
<p>Value: {value}</p>
147+
</div>
148+
);
149+
};

app/components/ui/number-input.tsx

Lines changed: 18 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import { NumberField } from '@base-ui-components/react';
22
import { ChevronDown, ChevronUp, Minus, Plus } from 'lucide-react';
3-
import { ComponentProps } from 'react';
3+
import { ComponentProps, useRef } from 'react';
44
import { useTranslation } from 'react-i18next';
55
import { match } from 'ts-pattern';
66

@@ -27,8 +27,10 @@ export const NumberInput = ({
2727
locale,
2828
buttons,
2929
className,
30+
onKeyDown,
3031
...props
3132
}: NumberInputProps) => {
33+
const inputRef = useRef<HTMLInputElement>(null);
3234
const { i18n } = useTranslation();
3335
const buttonSize = match(size)
3436
.with('default', undefined, null, () => 'icon' as const)
@@ -39,7 +41,20 @@ export const NumberInput = ({
3941
const _locale = locale ?? i18n.language;
4042

4143
return (
42-
<NumberField.Root {...props} locale={_locale} className={cn(className)}>
44+
<NumberField.Root
45+
invalid={!!ariaInvalid}
46+
{...props}
47+
locale={_locale}
48+
className={cn(className)}
49+
onKeyDown={(e) => {
50+
if (e.key === 'Enter') {
51+
// Make sure that the value is updated when pressing enter
52+
inputRef.current?.blur();
53+
inputRef.current?.focus();
54+
}
55+
onKeyDown?.(e);
56+
}}
57+
>
4358
<NumberField.Group className="flex gap-2">
4459
{buttons === 'mobile' && (
4560
<NumberField.Decrement
@@ -51,6 +66,7 @@ export const NumberInput = ({
5166
<NumberField.Input
5267
render={
5368
<Input
69+
ref={inputRef}
5470
endElement={
5571
buttons === 'classic' && (
5672
<NumberField.Group className="flex flex-col">
@@ -65,7 +81,6 @@ export const NumberInput = ({
6581
}
6682
size={size}
6783
placeholder={placeholder}
68-
aria-invalid={ariaInvalid}
6984
{...inputProps}
7085
/>
7186
}

0 commit comments

Comments
 (0)