T
TanStack9mo ago
like-gold

Spread properties over an input field

I am used to react hook form, and there you can connect an input by doing {...register('fieldName')}. Now the architecture is different on TSF, but is the a possibility to do something like:
<form.Field
name="firstName"
children={(field) => {
return (
<>
<label htmlFor={field.name}>First Name:</label>
// Spread field in input
<input {...field} />
<FieldInfo field={field} />
</>
)
}}
/>
<form.Field
name="firstName"
children={(field) => {
return (
<>
<label htmlFor={field.name}>First Name:</label>
// Spread field in input
<input {...field} />
<FieldInfo field={field} />
</>
)
}}
/>
4 Replies
absent-sapphire
absent-sapphire9mo ago
you'd probably need to implement your own register function that maps the props from field to what an input accepts
other-emerald
other-emerald9mo ago
yeah, you need to remap the field's fields, since it has handleChange, etc.. while input accepts onChange. Also, their definitions are different since onChange takes an event as an argument while handleChange takes the actual (typesafe) value
correct-apricot
correct-apricot9mo ago
You'd be best served using the form composition api and mapping it inside the fields component. Then it simply becomes this:
<form.AppField name="firstName" children={(field) => <field.TextField label="First Name:" />} />
<form.AppField name="firstName" children={(field) => <field.TextField label="First Name:" />} />
Personally, I don't even need a label prop on text fields anymore as I infer it by setting a convention for translations and use field.name to make the right translation key.
afraid-scarlet
afraid-scarlet9mo ago
We've intentionally not supported the spread operation of RHF, as it's an entirely different API that's actually not all that useful in production apps. Instead you're meant to do what @shoff suggested

Did you find this page helpful?