Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(core): docs for reusable fields & reusable field utility type #1084

Open
wants to merge 5 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
92 changes: 92 additions & 0 deletions docs/framework/react/guides/reusable-fields.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
---
id: reusable-fields
title: Creating reusable fields
---

As TanStack form is a headless library, we provide you the core building blocks and then give you the freedom to build on top of them. This page introduces the concept of creating reusable field-components for your form, allowing you to create fields that you can reuse throughout your app.

## Basic Usage

To create a reusable fields, you can do the following.

```tsx
import { InferValidFormKeys, UseFormReturnType } from '@tanstack/react-form';

export default function GenericTextField<
TForm,
TFormValidator
>({ name, form }: {
name: InferValidFormKeys<TForm, string>;
form: UseFormReturnType<TForm, TFormValidator>,
> }): JSX.Element {
return (
<form.Field name={name}>
{({ handleChange, handleBlur, state }) => (
<input
value={state.value}
onChange={(e) => handleChange(e.target.value as any)}
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Another improvement would be to get Ts to infer the handleChange value so the update is type safe.

onBlur={handleBlur}
/>
)}
</form.Field>
);
}
```

With the InferValidFormKeys the GenericTextField component's name prop will only accept the names of fields that have a valid value type, in this case a string, as shown here.

```tsx
name: InferValidFormKeys<TForm, string>;
```

Deep values can also be inferred using this method from the parent form.

```tsx
function App() {
const form = useForm({
defaultValues: { name: '', id: 0, interests: {hobbies: ''} },
onSubmit: ({ value }) => {
console.log(value);
},
});

return <GenericTextField form={form} name="interests.hobbies" />;
}
```

## Full Example

```tsx
import { InferValidFormKeys, UseFormReturnType } from '@tanstack/react-form';

export default function GenericTextField<
TForm,
TFormValidator
>({ name, form }: {
name: InferValidFormKeys<TForm, string>;
form: UseFormReturnType<TForm, TFormValidator>
> }): JSX.Element {
return (
<form.Field name={name}>
{({ handleChange, handleBlur, state }) => (
<input
value={state.value}
onChange={(e) => handleChange(e.target.value as any)}
onBlur={handleBlur}
/>
)}
</form.Field>
);
}

function App() {
const form = useForm({
defaultValues: { name: '', id: 0, interests: {hobbies: ''} },
onSubmit: ({ value }) => {
console.log(value);
},
});

return <GenericTextField form={form} name="name" />;
}
```
1 change: 1 addition & 0 deletions docs/reference/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ title: "@tanstack/form-core"
- [FormState](type-aliases/formstate.md)
- [FormValidateFn](type-aliases/formvalidatefn.md)
- [FormValidator](type-aliases/formvalidator.md)
- [InferValidFormKeys](type-aliases/infervalidformkeys.md)
- [StandardSchemaV1](type-aliases/standardschemav1.md)
- [Updater](type-aliases/updater.md)
- [UpdaterFn](type-aliases/updaterfn.md)
Expand Down
22 changes: 22 additions & 0 deletions docs/reference/type-aliases/infervalidformkeys.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
---
id: InferValidFormKeys
title: InferValidFormKeys
---

# Type Alias: InferValidFormKeys\<TForm, TFieldType\>

```ts
type InferValidFormKeys<TForm, TFieldType>: { [K in DeepKeys<TForm>]: DeepValue<TForm, K> extends TFieldType ? K : never }[DeepKeys<TForm>];
```

Infers the form keys of valid fields

## Type Parameters

• **TForm**

• **TFieldType**

## Defined in

[packages/form-core/src/util-types.ts:151](https://github.com/TanStack/form/blob/main/packages/form-core/src/util-types.ts#L151)
12 changes: 12 additions & 0 deletions packages/form-core/src/util-types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -144,3 +144,15 @@ export type DeepValue<
: never
: // Do not allow `TValue` to be anything else
never

/**
* Infers the form keys of valid fields
*/
export type InferValidFormKeys<
// Form generic slot
TForm,
// Desired type of the generic component
TFieldType,
> = {
[K in DeepKeys<TForm>]: DeepValue<TForm, K> extends TFieldType ? K : never
}[DeepKeys<TForm>]
11 changes: 10 additions & 1 deletion packages/react-form/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import type {
FieldApiOptions,
Validator,
} from '@tanstack/form-core'
import type { FunctionComponent } from 'react'
import { ReactFormExtendedApi } from './useForm'

/**
* The field options.
Expand All @@ -28,3 +28,12 @@ export type UseFieldOptions<
> & {
mode?: 'value' | 'array'
}

/**
* The return type use useForm with pre-populated generics
*/
export type UseFormReturnType<TForm, TFormValidator> = TFormValidator extends
Copy link
Contributor Author

@harry-whorlow harry-whorlow Dec 22, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I would love to get rid of the TFormValidator slot, since TFormValidator is just Validator<TForm, unknown> | undefined. But so far my efforts have been fruitless.

| Validator<TForm, unknown>
| undefined
? ReactFormExtendedApi<TForm, TFormValidator>
: never
Loading