Skip to content

Commit

Permalink
chore: fix helpers
Browse files Browse the repository at this point in the history
1. Fix `getInputProps` to return a `defaultValue` if the `defaultValue`
is a number
2. Fix `getInputProps` to return `defaultValue` instead of `value` for
`checkbox` and `radio` input types
3. Fix `getCollectionProps` to return `defaultValue` instead of `value`
  • Loading branch information
lifeiscontent committed Apr 25, 2024
1 parent e1c28cb commit a251d54
Showing 1 changed file with 14 additions and 10 deletions.
24 changes: 14 additions & 10 deletions packages/conform-react/helpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,6 @@ type InputProps = Pretty<
step?: string | number;
pattern?: string;
multiple?: boolean;
value?: string;
defaultChecked?: boolean;
defaultValue?: string;
}
Expand Down Expand Up @@ -258,13 +257,16 @@ 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.defaultValue =
typeof options.value === 'string' ? options.value : 'on';
props.defaultChecked =
typeof metadata.initialValue === 'boolean'
? metadata.initialValue
: metadata.initialValue === props.value;
: metadata.initialValue === props.defaultValue;
} else if (typeof metadata.initialValue === 'string') {
props.defaultValue = metadata.initialValue;
} else if (typeof metadata.initialValue === 'number') {
props.defaultValue = metadata.initialValue.toString();
}
}

Expand Down Expand Up @@ -383,20 +385,22 @@ export function getCollectionProps<
metadata: FieldMetadata<Schema, any, any>,
options: Options,
): Array<
InputProps & Pick<Options, 'type'> & Pick<Required<InputProps>, 'value'>
InputProps &
Pick<Options, 'type'> &
Pick<Required<InputProps>, 'defaultValue'>
> {
return options.options.map((value) =>
return options.options.map((defaultValue) =>
simplify({
...getFormControlProps(metadata, options),
key: `${metadata.key ?? ''}${value}`,
id: `${metadata.id}-${value}`,
key: `${metadata.key ?? ''}${defaultValue}`,
id: `${metadata.id}-${defaultValue}`,
type: options.type,
value,
defaultValue,
defaultChecked:
typeof options.value === 'undefined' || options.value
? options.type === 'checkbox' && Array.isArray(metadata.initialValue)
? metadata.initialValue.includes(value)
: metadata.initialValue === value
? metadata.initialValue.includes(defaultValue)
: metadata.initialValue === defaultValue
: undefined,

// The required attribute doesn't make sense for checkbox group
Expand Down

0 comments on commit a251d54

Please sign in to comment.