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: 2 comments
-
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.
Is this what you are looking for?