Skip to content

Commit

Permalink
fix: getInputProps
Browse files Browse the repository at this point in the history
  • Loading branch information
lifeiscontent committed Aug 9, 2024
1 parent e23198a commit 24baf23
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 9 deletions.
23 changes: 14 additions & 9 deletions packages/conform-react/helpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -232,10 +232,10 @@ export function getFormControlProps<Schema>(
* ```tsx
* // To setup an uncontrolled input
* <input {...getInputProps(metadata, { type: 'text' })} />
* // To setup an input without defaultValue
* <input {...getInputProps(metadata, { type: 'text', value: false })} />
* // To setup an uncontrolled checkbox
* <input {...getInputProps(metadata, { type: 'checkbox' })} />
* // To setup an input without defaultValue
* <input {...getInputProps(metadata, { value: false })} />
* // To setup a radio button without defaultChecked state
* <input {...getInputProps(metadata, { type: 'radio', value: false })} />
* ```
Expand All @@ -257,13 +257,18 @@ export function getInputProps<Schema, Options extends InputOptions>(
};

if (typeof options.value === 'undefined' || options.value) {
if (options.type === 'checkbox' || options.type === 'radio') {
props.value = typeof options.value === 'string' ? options.value : 'on';
props.defaultChecked = Array.isArray(metadata.initialValue)
? metadata.initialValue.includes(options.value)
: metadata.initialValue === props.value;
} else if (typeof metadata.initialValue === 'string') {
props.defaultValue = metadata.initialValue;
switch (options.type) {
case 'checkbox':
case 'radio':
props.value = typeof options.value === 'string' ? options.value : 'on';
props.defaultChecked = Array.isArray(metadata.initialValue)
? metadata.initialValue.includes(options.value)
: metadata.initialValue === props.value;
break;
case 'file':
break;
default:
props.defaultValue = metadata.initialValue?.toString();
}
}

Expand Down
11 changes: 11 additions & 0 deletions tests/conform-react.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -155,6 +155,17 @@ describe('conform-react', () => {
...props,
type: 'file',
});
expect(
getInputProps(
// This happens in Playwright
// @ts-expect-error FIXME: To fix the type
{ ...metadata, initialValue: [undefined, undefined] },
{ type: 'file' },
),
).toEqual({
...props,
type: 'file',
});
});

test('getTextareaProps', () => {
Expand Down

0 comments on commit 24baf23

Please sign in to comment.