Skip to content

Commit

Permalink
[@mantine/core] NumberInput: Improve onChange handler to be called …
Browse files Browse the repository at this point in the history
…with number unless the input is empty (#5037)
  • Loading branch information
rtivital committed Nov 12, 2023
1 parent bff2e0e commit b315aba
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 7 deletions.
19 changes: 19 additions & 0 deletions src/mantine-core/src/components/NumberInput/NumberInput.story.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,25 @@ export function Usage() {
);
}

export function OnChangeValue() {
const [value, setValue] = useState<number | string>(345);
return (
<div style={{ padding: 40 }}>
<NumberInput
value={value}
label="Number input"
placeholder="Number input"
suffix="suf"
prefix="pref"
thousandSeparator
onChange={setValue}
/>
{typeof value === 'number' ? `${value} number` : `${value === '' ? 'empty' : value} string`}
<Button onClick={() => setValue(245.32)}>Set value to float</Button>
</div>
);
}

export function RightSectionSizes() {
return (
<div
Expand Down
10 changes: 3 additions & 7 deletions src/mantine-core/src/components/NumberInput/NumberInput.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -25,8 +25,8 @@ export interface NumberInputHandlers {
decrement: () => void;
}

function isValidNumber(value: number | undefined): value is number {
return typeof value === 'number' && !Number.isNaN(value);
function isValidNumber(value: number | string | undefined): value is number {
return (typeof value === 'number' || !Number.isNaN(Number(value))) && !Number.isNaN(value);
}

interface GetDecrementedValueInput {
Expand Down Expand Up @@ -231,11 +231,7 @@ export const NumberInput = factory<NumberInputFactory>((_props, ref) => {
});

const handleValueChange: OnValueChange = (payload, event) => {
setValue(
typeof _value === 'number' && isValidNumber(payload.floatValue)
? payload.floatValue
: payload.value
);
setValue(isValidNumber(payload.floatValue) ? payload.floatValue : payload.value);
onValueChange?.(payload, event);
};

Expand Down

0 comments on commit b315aba

Please sign in to comment.