Skip to content

Commit

Permalink
Merge pull request #8454 from marmelab/fix-NumberInput-parse-0
Browse files Browse the repository at this point in the history
Fix `<NumberInput>` parses 0 as string when used with a custom `parse` prop
  • Loading branch information
djhi authored Dec 1, 2022
2 parents 48cbe2d + d75f2c7 commit 59e8b80
Show file tree
Hide file tree
Showing 2 changed files with 54 additions and 7 deletions.
44 changes: 44 additions & 0 deletions packages/ra-ui-materialui/src/input/NumberInput.spec.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -292,6 +292,50 @@ describe('<NumberInput />', () => {
expect(onSubmit.mock.calls[0][0].views).toBeNull();
});

it('should cast value to a numeric with a custom parse function', async () => {
const onSubmit = jest.fn();

render(
<AdminContext>
<SimpleForm toolbar={<MyToolbar />} onSubmit={onSubmit}>
<NumberInput {...defaultProps} parse={value => value} />
</SimpleForm>
</AdminContext>
);
const input = screen.getByLabelText('resources.posts.fields.views');
fireEvent.change(input, { target: { value: '12' } });
fireEvent.click(screen.getByText('ra.action.save'));
await waitFor(() => {
expect(onSubmit).toHaveBeenCalledWith(
{ views: 12 },
expect.anything()
);
});
expect(typeof onSubmit.mock.calls[0][0].views).toEqual('number');
});

it('should cast 0 to a numeric with a custom parse function', async () => {
const onSubmit = jest.fn();

render(
<AdminContext>
<SimpleForm toolbar={<MyToolbar />} onSubmit={onSubmit}>
<NumberInput {...defaultProps} parse={value => value} />
</SimpleForm>
</AdminContext>
);
const input = screen.getByLabelText('resources.posts.fields.views');
fireEvent.change(input, { target: { value: '0' } });
fireEvent.click(screen.getByText('ra.action.save'));
await waitFor(() => {
expect(onSubmit).toHaveBeenCalledWith(
{ views: 0 },
expect.anything()
);
});
expect(typeof onSubmit.mock.calls[0][0].views).toEqual('number');
});

it('should reformat if format function gets changed', async () => {
const AngleInput = props => {
const unit = useWatch({ name: 'unit' });
Expand Down
17 changes: 10 additions & 7 deletions packages/ra-ui-materialui/src/input/NumberInput.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -83,13 +83,16 @@ export const NumberInput = ({
}
const target = event.target;
setValue(target.value);
const newValue = target.valueAsNumber
? parse
? parse(target.valueAsNumber)
: target.valueAsNumber
: parse
? parse(target.value)
: convertStringToNumber(target.value);
const newValue =
target.valueAsNumber !== undefined &&
target.valueAsNumber !== null &&
!isNaN(target.valueAsNumber)
? parse
? parse(target.valueAsNumber)
: target.valueAsNumber
: parse
? parse(target.value)
: convertStringToNumber(target.value);
field.onChange(newValue);
};

Expand Down

0 comments on commit 59e8b80

Please sign in to comment.