feat: Allow restricting field component to field value
Related issue: #1506
This PR implements a way to create 'branded' field components. Those special field components may only be used if the AppField's value matches it.
TODOS
- [ ] Can it be generic somehow? Can the component access that?
- [ ] Check need for implementation (and implement)
- [x] React
- [ ] Solid
- [ ] Angular
- [ ] Amend documentation of Form Composition
- [ ] React
- [ ] Solid
- [ ] Angular
- [ ] Unit tests
The issue
interface TextFieldProps {
label: string
}
function TextField(props: TextFieldProps) {
// we assume our field will be of type string
const field = useFieldContext<string>();
return <></>;
}
const { useAppForm } = createFormHook({
fieldContext,
formContext,
fieldComponents: {
TextField
},
formComponents: {},
})
function App() {
const form = useAppForm({
defaultValues: {
a: '',
b: 0,
},
})
return (
<>
<form.AppField name="a">
{(field) => {
// okay, because 'a' is a string
return <field.TextField label="" />;
}}
</form.AppField>
<form.AppField name="b">
{(field) => {
// oops! 'b' is a number, not a string. No error shows up
return <field.TextField label="" />;
}}
</form.AppField>
</>
)
}
The solution
The PR addresses it as follows (feedback is appreciated!):
interface TextFieldProps {
label: string
}
function TextField(props: TextFieldProps) {
// we assume our field will be of type string
const field = useFieldContext<string>();
return <></>;
}
// we're creating a field component restricted to strings, with the properties of TextFieldProps
const TextFieldComponent = createFieldComponent<string, TextFieldProps>(TextField);
const { useAppForm } = createFormHook({
fieldContext,
formContext,
fieldComponents: {
TextField: TextFieldComponent,
OldTextField: TextField
},
formComponents: {},
})
function App() {
const form = useAppForm({
defaultValues: {
a: '',
b: 0,
},
})
return (
<>
<form.AppField name="a">
{(field) => (
<>
{/* Okay, because 'a' is a string */}
<field.TextField label="" />
<field.OldTextField label="" />
</>
)}
</form.AppField>
<form.AppField name="b">
{(field) => (
<>
{/* Error! TextField cannot be used on number fields */}
<field.TextField label="" />
{/* Directly passed compoents are considered 'global' */}
<field.OldTextField />
</>
}}
</form.AppField>
</>
)
}
🤖 Nx Cloud AI Fix Eligible
An automatically generated fix could have helped fix failing tasks for this run, but Self-healing CI is disabled for this workspace. Visit workspace settings to enable it and get automatic fixes in future runs.
To disable these notifications, a workspace admin can disable them in workspace settings.
View your CI Pipeline Execution ↗ for commit a8231cc4602311219bf053655745389aff6e1147
| Command | Status | Duration | Result |
|---|---|---|---|
nx affected --targets=test:sherif,test:knip,tes... |
❌ Failed | 29s | View ↗ |
nx run-many --target=build --exclude=examples/** |
❌ Failed | 4s | View ↗ |
☁️ Nx Cloud last updated this comment at 2025-10-05 12:25:05 UTC
More templates
- @tanstack/form-example-angular-array
- @tanstack/form-example-angular-large-form
- @tanstack/form-example-angular-simple
- @tanstack/form-example-lit-simple
- @tanstack/form-example-lit-ui-libraries
- @tanstack/form-example-react-array
- @tanstack/form-example-react-compiler
- @tanstack/field-errors-from-form-validators
- @tanstack/form-example-react-large-form
- @tanstack/form-example-react-next-server-actions
- @tanstack/form-example-react-query-integration
- @tanstack/form-example-remix
- @tanstack/form-example-react-simple
- @tanstack/form-example-react-standard-schema
- @tanstack/form-example-react-tanstack-start
- @tanstack/form-example-react-ui-libraries
- @tanstack/form-example-solid-array
- @tanstack/form-example-solid-large-form
- @tanstack/form-example-solid-simple
- @tanstack/form-example-svelte-array
- @tanstack/form-example-svelte-simple
- @tanstack/form-example-vue-array
- @tanstack/form-example-vue-simple
@tanstack/angular-form
npm i https://pkg.pr.new/@tanstack/angular-form@1606
@tanstack/form-core
npm i https://pkg.pr.new/@tanstack/form-core@1606
@tanstack/lit-form
npm i https://pkg.pr.new/@tanstack/lit-form@1606
@tanstack/react-form
npm i https://pkg.pr.new/@tanstack/react-form@1606
@tanstack/solid-form
npm i https://pkg.pr.new/@tanstack/solid-form@1606
@tanstack/svelte-form
npm i https://pkg.pr.new/@tanstack/svelte-form@1606
@tanstack/vue-form
npm i https://pkg.pr.new/@tanstack/vue-form@1606
commit: 24f9ef3
Codecov Report
Attention: Patch coverage is 33.33333% with 2 lines in your changes missing coverage. Please review.
Project coverage is 43.03%. Comparing base (
6510d8b) to head (24f9ef3). Report is 2 commits behind head on main.
| Files with missing lines | Patch % | Lines |
|---|---|---|
| packages/react-form/src/createFormHook.tsx | 33.33% | 2 Missing :warning: |
Additional details and impacted files
@@ Coverage Diff @@
## main #1606 +/- ##
===========================================
- Coverage 89.55% 43.03% -46.52%
===========================================
Files 34 13 -21
Lines 1493 158 -1335
Branches 370 26 -344
===========================================
- Hits 1337 68 -1269
+ Misses 139 79 -60
+ Partials 17 11 -6
:umbrella: View full report in Codecov by Sentry.
:loudspeaker: Have feedback on the report? Share it here.
:rocket: New features to boost your workflow:
- :snowflake: Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
- :package: JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.
Wow. You'd think if one misclick is able to mark a PR as ready for review, you'd have the option to mark it as draft on mobile.
Doesn't seem to be possible. I'll mark it as draft again when I'm on desktop ...
The current implementation works great for simple types, and I could certainly make use of it for my most common form fields to cut down on some boilerplate and current need to pass field or value into the component for "full" type safety.
What were you wondering about specifically in terms of generics?
I've had a play with trying to register a generic form components similar to <RecordSelect /> which has a value of TValue | null (where TValue extends { id: string; })
After registering the component, it's fairly straightforward to define various simple data shapes that extend {id: string;} and store them in form fields. These easily qualify for the generic field.RecordSelect because they satisfy AppFieldComponentsOfType.
However, the component ends up locked to a strict option type of { id: string; }
I'm no library-level TS wizard so I'm a bit grasping at straws for we'd ever be able to inject the correct type values into these generic components at the AppField level, where we know the concrete TData we're dealing with. Perhaps there's an approach where we're registering functions conforming to a certain signature which in turn return components, instead of registering the components themselves? (This is more "can we do it?" than "should we do it?" thinking)
You mean a case where the component has properties that should adapt to the field value using it?
Yeah, that is very difficult in the current iteration of this PR, which is why it has been stale while I consider some other options.
A simple example of this would also be Radio buttons. The value of the radio button should not be string, but restricted to the field value using it (Example: 'a' | 'b'). A generic component solves this very easily, but this implementation cannot be compatible with it.
Yes, Radio and a basic Select (constrained to a string union) are simpler examples of the challenges here.
This crude API seems to work in my application code, the challenge would obviously be to feed createGenericFoo functions into createFormHook() and get properly-scoped GenericFoo components outputted on AppField
function makeCreateGenericFieldComponent<
TBaseFieldValue, // For use in AppFieldComponentsOfType or an equivalent helper
TGetScopedComponent extends <T extends TBaseFieldValue>(value: T) => React.FC<any>, // Allows us to get the scoped component once we know the field value
>(args: { baseFieldValue: TBaseFieldValue; getScopedComponent: TGetScopedComponent }) {
return args
}
// We would want to somehow pass this into createFormHook
const createGenericSelect = makeCreateGenericFieldComponent({
baseFieldValue: '' as string,
getScopedComponent: <TValue extends string>(value: TValue) => {
return Select<TValue>
},
})
// We would want something like this to happen inside AppField once we have access to the field value
const myAnimal = "dog" as "dog" | "cat" | "bird";
const AnimalSelect = createGenericSelect.getScopedComponent(myAnimal);
// ^ yay correctly inferred as Select<"dog" | "cat" | "bird">
For this UI element:
type SelectFieldProps<TValue extends string> = {
label: string
options: readonly TValue[]
getOptionLabel?: (option: TValue) => string
}
function Select<TValue extends string>({
label,
options,
getOptionLabel,
}: SelectFieldProps<TValue>) {
const field = useFieldContext<TValue>()
return (
<label>
<div>{label}</div>
<select
value={field.state.value}
onChange={(e) => {
const option = options.find((o) => o === e.target.value)
if (!option) throw new Error('Invariant')
field.handleChange(option)
}}
>
{options.map((option, index) => (
<option key={index} value={option}>
{getOptionLabel ? getOptionLabel(option) : option}
</option>
))}
</select>
</label>
)
}
Sounds interesting! After some other PR work, I'll freshen this one up a bit and see if I can find a nice solution for it.
⚠️ No Changeset found
Latest commit: a8231cc4602311219bf053655745389aff6e1147
Merging this PR will not cause a version bump for any packages. If these changes should not result in a new version, you're good to go. If these changes should result in a version bump, you need to add a changeset.
This PR includes no changesets
When changesets are added to this PR, you'll see the packages that this PR includes changesets for and the associated semver types
Click here to learn what changesets are, and how to add one.
Click here if you're a maintainer who wants to add a changeset to this PR
Have you looked at this approach - https://github.com/TanStack/form/discussions/1240 , I feel using this approach is a much simpler option than to create this type mapping
It is much simpler, but as you saw, the field assignment would only serve for type inference and is not a prop that is passed at all. That's why this PR tried to check out alternative approaches.