Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: getInputProps #734

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
Loading