Skip to content

Commit

Permalink
Use parse instead of format when calculating checked
Browse files Browse the repository at this point in the history
  • Loading branch information
jharding committed Feb 14, 2022
1 parent dcf306b commit 9839445
Show file tree
Hide file tree
Showing 2 changed files with 90 additions and 2 deletions.
88 changes: 88 additions & 0 deletions src/Field.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -1249,3 +1249,91 @@ describe("Field", () => {
console.error.mockRestore();
});
});

it("should support using format/parse with radio controls", () => {
const format = (value) => value && value.toString();
const parse = (value) => value && parseInt(value, 10);

const { getByTestId } = render(
<Form onSubmit={onSubmitMock} initialValues={{ number: 20 }}>
{({ handleSubmit }) => (
<form onSubmit={handleSubmit}>
<Field
name="number"
component="input"
type="radio"
value={10}
data-testid="ten"
parse={parse}
format={format}
/>
<Field
name="number"
component="input"
type="radio"
value={20}
data-testid="twenty"
parse={parse}
format={format}
/>
<Field
name="number"
component="input"
type="radio"
value={30}
data-testid="thirty"
parse={parse}
format={format}
/>
</form>
)}
</Form>,
);
expect(getByTestId("ten").checked).toBe(false);
expect(getByTestId("twenty").checked).toBe(true);
expect(getByTestId("thirty").checked).toBe(false);
});

it("should support using format/parse with checkbox controls", () => {
const format = (value) => value && value.map((x) => x.toString());
const parse = (value) => value && value.map((x) => parseInt(x, 10));

const { getByTestId } = render(
<Form onSubmit={onSubmitMock} initialValues={{ number: [20, 30] }}>
{({ handleSubmit }) => (
<form onSubmit={handleSubmit}>
<Field
name="number"
component="input"
type="checkbox"
value={10}
data-testid="ten"
parse={parse}
format={format}
/>
<Field
name="number"
component="input"
type="checkbox"
value={20}
data-testid="twenty"
parse={parse}
format={format}
/>
<Field
name="number"
component="input"
type="checkbox"
value={30}
data-testid="thirty"
parse={parse}
format={format}
/>
</form>
)}
</Form>,
);
expect(getByTestId("ten").checked).toBe(false);
expect(getByTestId("twenty").checked).toBe(true);
expect(getByTestId("thirty").checked).toBe(true);
});
4 changes: 2 additions & 2 deletions src/useField.js
Original file line number Diff line number Diff line change
Expand Up @@ -161,14 +161,14 @@ function useField<FormValues: FormValuesShape>(
get checked() {
let value = state.value;
if (type === "checkbox") {
value = format(value, name);
value = parse(value, name);
if (_value === undefined) {
return !!value;
} else {
return !!(Array.isArray(value) && ~value.indexOf(_value));
}
} else if (type === "radio") {
return format(value, name) === _value;
return parse(value, name) === _value;
}
return undefined;
},
Expand Down

0 comments on commit 9839445

Please sign in to comment.