Form with conditional fields based on type #645
-
Hey, A common use case is to render different form controls based on some type, Here's a starting point following #451 but I got into some issues with the paths. https://stackblitz.com/edit/stackblitz-starters-mwyz3h?file=app%2Fexample%2Fform.tsx
If there's any working example or some guidelines it'll be very helpful, Best, |
Beta Was this translation helpful? Give feedback.
Replies: 4 comments 1 reply
-
Is this what you are looking for? export function EmailForm() {
const [lastResult, action] = useFormState(login, undefined);
const [form, fields] = useForm({
defaultValue: {
type: 'smtp',
config: {
host: 'smtp.foo.com',
},
},
// Sync the result of last submission
lastResult,
// Reuse the validation logic on the client
onValidate({ formData }) {
return parseWithZod(formData, { schema: appEmailConfigSchema });
},
// Validate the form on blur event triggered
shouldValidate: 'onBlur',
shouldRevalidate: 'onInput',
});
// To access fields of the `config` object
const configFieldset = fields.config.getFieldset();
// You can now access the `host` field with `configFieldset`
console.log('name', configFieldset.host.name);
console.log('value', configFieldset.host.initialValue);
return (
<form id={form.id} onSubmit={form.onSubmit} action={action} noValidate>
<div>
<label>Email</label>
<input
type="email"
key={configFieldset.host.key}
name={configFieldset.host.name}
defaultValue={configFieldset.host.initialValue}
/>
<div>{configFieldset.host.errors}</div>
</div>
<button>Submit</button>
</form>
);
} |
Beta Was this translation helpful? Give feedback.
-
yea thanks, for anyone who's interested, following is a working example of a dynamic form based on type selection with validation and everything. https://stackblitz.com/edit/stackblitz-starters-qcmaga?file=app%2Fpage.tsx |
Beta Was this translation helpful? Give feedback.
-
@edmundhung this discussion works up to version 1.1.3, upgrading to 1.1.5 breaks union, Another thing with fieldset in 1.1.3: const configFieldset: Required<{
token?: FieldMetadata<string | undefined, {
type: "sendgrid";
config: {
token: string;
};
} | {
type: "smtp";
config: {
host: string;
};
}, string[]> | undefined;
host?: FieldMetadata<...> | undefined;
}> fieldset in 1.1.5: const fields: Required<{
type: FieldMetadata<string, {
type: string;
config: {
host: string;
};
}, string[]>;
config: FieldMetadata<{
host: string;
}, {
type: string;
config: {
host: string;
};
}, string[]>;
}> |
Beta Was this translation helpful? Give feedback.
-
@edmundhung any news about this? it started to break only on 1.1.5 which is just 2 minor versions up from a working version. thanks! |
Beta Was this translation helpful? Give feedback.
Is this what you are looking for?