### Install Updated Dependencies
Source: https://github.com/final-form/react-final-form/blob/main/MIGRATION_V7.md
Update react-final-form and final-form to their respective major versions.
```bash
npm install react-final-form@^7.0.0 final-form@^5.0.0
```
--------------------------------
### Install React Final Form with npm
Source: https://github.com/final-form/react-final-form/blob/main/docs/getting-started.md
Use this command to add final-form and react-final-form to your project dependencies using npm.
```bash
npm install --save final-form react-final-form
```
--------------------------------
### Implement render prop
Source: https://github.com/final-form/react-final-form/blob/main/docs/types/FormProps.md
Example of using the render prop to access form state and custom props.
```tsx
}}
/>
```
--------------------------------
### Install React Final Form with yarn
Source: https://github.com/final-form/react-final-form/blob/main/docs/getting-started.md
Use this command to add final-form and react-final-form to your project dependencies using yarn.
```bash
yarn add final-form react-final-form
```
--------------------------------
### Create a React Final Form Decorator
Source: https://github.com/final-form/react-final-form/blob/main/docs/migration/redux-form.md
This is a 'cheat code' example for creating a decorator that mimics Redux Form's `reduxForm()` decorator. It is not recommended for production use due to potential technical debt.
```jsx
import { Form } from 'react-final-form'
const reactFinalForm = ({ form, ...config }) => component => props => (
)
```
--------------------------------
### Basic React Final Form Structure
Source: https://github.com/final-form/react-final-form/blob/main/docs/getting-started.md
This example demonstrates the basic structure of a form using React Final Form, including the Form and Field components. It shows how to define fields, use different rendering strategies, and handle form submission.
```jsx
import { Form, Field } from 'react-final-form'
const MyForm = () => (
)}
/>
)
```
--------------------------------
### Render Function Example
Source: https://github.com/final-form/react-final-form/blob/main/docs/types/FieldProps.md
A render function that receives `FieldRenderProps` and other arbitrary props. If `render` and `children` are both specified, `render` is called with `children` as an additional prop.
```tsx
{
console.log(props.someArbitraryOtherProp) // would print 42
return
}}
/>
```
--------------------------------
### Create a Form component equivalent to Formik's
Source: https://github.com/final-form/react-final-form/blob/main/docs/migration/formik.md
This example shows how to create a custom Form component in React Final Form that mimics Formik's `` component by preventing default form submission and calling `form.submit()`.
```jsx
import { useForm } from 'react-final-form'
const FormLikeFormik = props => {
const form = useForm()
return (
)}
```
--------------------------------
### Create a Higher-Order Component for React Final Form
Source: https://github.com/final-form/react-final-form/blob/main/docs/faq.md
Demonstrates how to wrap a component using the render prop pattern to achieve HOC functionality, allowing access to injected props in lifecycle methods.
```jsx
import { Form, Field } from 'react-final-form'
class MyForm extends React.Component {
componentDidMount() {
const { initialize } = this.props // access to injected props
ajax.fetch('/myData').then(data => initialize(data))
}
render() {
return
}
}
// 👇 THIS LINE IS THE HOC 👇
export default props =>
```
--------------------------------
### Define AnyObject Locally
Source: https://github.com/final-form/react-final-form/blob/main/MIGRATION_V7.md
AnyObject is no longer exported from the package. Define it locally as a Record.
```typescript
import { AnyObject } from 'react-final-form';
```
```typescript
// Define locally:
type AnyObject = Record;
```
--------------------------------
### Migrate configuration props to Form component
Source: https://github.com/final-form/react-final-form/blob/main/docs/migration/redux-form.md
Move form configuration like initialValues, onSubmit, and validate from the reduxForm HOC to the component props.
```diff
import React from 'react'
import { Form, Field } from 'react-final-form'
const MyForm = props => {
const { handleSubmit, pristine, reset, submitting } = props
return (
)}
)
}
export default reduxForm({
form: 'myForm',
- initialValues: {
- firstName: 'Dan'
- },
- onSubmit: values => {
- // send values to the cloud
- },
- validate: values => {
- // do validation here, and return errors object
- }
})(MyForm)
```
--------------------------------
### Handling Numeric Keys in Form Values
Source: https://github.com/final-form/react-final-form/blob/main/docs/faq.md
Convert numeric keys to string-prefixed keys before initialization and revert them upon form submission to bypass setIn engine limitations.
```jsx
const stringifyKeys = values =>
Object.keys(values).reduce((result, key) => {
result[`key${key}`] = values[key]
return result
}, {})
const destringifyKeys = values =>
Object.keys(values).reduce((result, key) => {
result[Number(key.substring(3))] = values[key]
return result
}, {})
```
--------------------------------
### FormSpyProps Configuration
Source: https://github.com/final-form/react-final-form/blob/main/docs/types/FormSpyProps.md
Details on the available props for the FormSpy component, including rendering methods and subscription management.
```APIDOC
## FormSpyProps
### Description
Configuration props for the component. If no onChange callback is provided, one of component, render, or children must be specified.
### Parameters
#### Props
- **children** (function) - Optional - A render function (props: FormRenderProps) => React.Node. Will not be called if onChange is specified.
- **component** (React.ComponentType) - Optional - A component that receives FormSpyRenderProps as props. Will not be called if onChange is specified.
- **onChange** (function) - Optional - A listener (formState: FormState) => void called when subscribed state changes. If provided, FormSpy will not render anything.
- **render** (function) - Optional - A render function (props: FormSpyRenderProps) => React.Node. Will not be called if onChange is specified.
- **subscription** (object) - Optional - An object of { [string]: boolean } defining which parts of FormState to subscribe to. Defaults to all state changes.
```
--------------------------------
### useForm return type
Source: https://github.com/final-form/react-final-form/blob/main/docs/api/useForm.md
The useForm hook returns the FormApi instance.
```ts
() => FormApi
```
--------------------------------
### Define initialValues
Source: https://github.com/final-form/react-final-form/blob/main/docs/types/FormProps.md
The initial values used to calculate pristine and dirty states.
```ts
FormValues | Object
```
--------------------------------
### FormProps Configuration
Source: https://github.com/final-form/react-final-form/blob/main/docs/types/FormProps.md
Configuration properties for the component.
```APIDOC
## FormProps
### Description
Configuration properties passed to the component to manage form state, rendering, and submission.
### Parameters
- **children** (function | React.Node) - Optional - Render function or node. Receives FormRenderProps.
- **component** (React.ComponentType) - Optional - Component to render. Receives FormRenderProps.
- **debug** (function) - Optional - Callback receiving (state, fieldStates) on every change.
- **decorators** (Array) - Optional - Array of decorators to apply to the form.
- **form** (FormApi) - Optional - Advanced: custom Final Form instance.
- **initialValues** (Object) - Optional - Initial form values.
- **initialValuesEqual** (function) - Optional - Predicate to determine if initialValues changed.
- **keepDirtyOnReinitialize** (boolean) - Optional - If true, only overwrites pristine values on reinitialize.
- **mutators** (Object) - Optional - Named mutator functions.
- **onSubmit** (function) - Required - Function called on form submission. Receives (values, form, callback).
```
--------------------------------
### Field Configuration Parameter
Source: https://github.com/final-form/react-final-form/blob/main/docs/api/useField.md
The optional configuration object for the field.
```typescript
UseFieldConfig
```
--------------------------------
### beforeSubmit Callback
Source: https://github.com/final-form/react-final-form/blob/main/docs/types/FieldProps.md
A function executed before onSubmit; returning false aborts the submission process.
```ts
() => void | false
```
--------------------------------
### Wrap form component with Form provider
Source: https://github.com/final-form/react-final-form/blob/main/docs/migration/redux-form.md
Encapsulate the existing form structure within the render prop component.
```diff
import React from 'react'
import { Form, Field } from 'react-final-form'
const MyForm = props => {
const { handleSubmit, pristine, reset, submitting } = props
return (
+
+ )}
+
)
}
```
--------------------------------
### Field API Documentation
Source: https://github.com/final-form/react-final-form/blob/main/docs/types/FieldProps.md
This section details the available props for the \`\` component in React Final Form.
```APIDOC
## Field Component Props
This document outlines the various properties that can be passed to the `` component in React Final Form.
### `name`
* **Type**: `string`
* **Required**: Yes
* **Description**: The name of your field. Field values may be deeply nested using dot-and-bracket syntax. [Learn more about Field Names](/docs/final-form/field-names).
### `parse`
* **Type**: `(value: any, name: string) => any`
* **Required**: Optional
* **Description**: A function that takes the value from the input and name of the field and converts the value into the value you want stored as this field's value in the form. Common usecases include converting strings into `Number`s or parsing localized dates into actual javascript `Date` objects. Almost always used in conjunction with [`format`](#format).
* **Note**: If you would like to override the default behavior of converting `''` to `undefined`, you can pass an [identity function](https://en.wikipedia.org/wiki/Identity_function), `v => v`, to `parse`, thus allowing you to have form values of `''`.
### `ref`
* **Description**: The `ref` is forwarded to the component provided by the `component` prop.
### `render`
* **Type**: `(props: FieldRenderProps) => React.Node`
* **Required**: Optional (if you specify [`component`](#component) or [`children`](#children))
* **Description**: A render function that is given [`FieldRenderProps`](FieldRenderProps), as well as any non-API props passed into the `` component. For example, if you did...
```tsx
{
console.log(props.someArbitraryOtherProp) // would print 42
return
}}
/>
```
* **Note**: If you specify `render` _and_ [`children`](#children), `render` will be called, with `children` injected as if it were an additional prop.
* **Related**: [`FieldRenderProps`](FieldRenderProps)
### `subscription`
* **Type**: `{ [string]: boolean }`
* **Required**: Optional (Advanced Usage)
* **Description**: An object of the parts of [`FieldState`](/docs/final-form/types/FieldState) to subscribe to. If a subscription is provided, the `[`](../api/Field) will only rerender when those parts of field state change. If no `subscription` is provided, it will default to subscribing to _all_ field state changes. i.e. `[`](../api/Field) will rerender whenever any part of the field state changes.
* **Related**: [`FieldState`](/docs/final-form/types/FieldState)
### `type`
* **Type**: `string`
* **Required**: Optional
* **Description**: If set to `"checkbox"` or `"radio"`, React Final Form will know to manage your values as a checkbox or radio button respectively. Results in a `checked` boolean inside the `input` value given to your render prop. It will be added on your input component, or you may retrieve its value inside the "input" property of your custom components.
### `validate`
* **Type**: `(value: ?any, allValues: Object, meta: ?FieldState) => ?any`
* **Required**: Optional
* **Description**: A function that takes the field value, all the values of the form and the `meta` data about the field and returns an error if the value is invalid, or `undefined` if the value is valid.
* **⚠️ IMPORTANT ⚠️**: By default, in order to allow inline fat-arrow validation functions, the field will not rerender if you change your validation function to an alternate function that has a different behavior. If you need your field to rerender with a new validation function, you will need to update another prop on the `Field`, such as `key`. See the following sandbox for an example: [](https://codesandbox.io/s/changing-field-level-validators-zc8ei?fontsize=14)
### `validateFields`
* **Type**: `string[]`
* **Required**: Optional
* **Description**: An array of field names to validate when this field changes. If `undefined`, _every_ field will be validated when this one changes; if `[]`, _only this field_ will have its field-level validation function called when it changes; if other field names are specified, those fields _and this one_ will be validated when this field changes.
* **⚠️ IMPORTANT ⚠️**: By default, in order to allow inline `[]` syntax, the field will not rerender if you change your `validateFields` prop changes. If you need your field to rerender with a new `validateFields` setting, you will need to update another prop on the `Field`, such as `key`.
### `value`
* **Type**: `any`
* **Required**: Optional
* **Description**: This is only used for checkboxes and radio buttons! You must also include a `type="radio"` or `type="checkbox"` prop.
* **Radio Buttons**: The value of the radio button. The radio button will render as `checked` if and only if the value given here `===` the value for the field in the form.
* **Checkboxes**:
* **With `value`**: The checkbox will be `checked` if the value given in `value` is contained in the array that is the value for the field for the form. Checking the box will add the value to the array, and unchecking the checkbox will remove the value from the array.
* **Without `value`**: The checkbox will be `checked` if the value is truthy. Checking the box will set the value to `true`, and unchecking the checkbox will set the value to `false`.
```
--------------------------------
### FieldProps API Documentation
Source: https://github.com/final-form/react-final-form/blob/main/docs/types/FieldProps.md
Documentation for the various props that can be passed to the `` component in React Final Form.
```APIDOC
## FieldProps
These are props that you pass to [``](../api/Field). You must provide one of the ways to render: `component`, `render`, or `children`.
### `afterSubmit`
#### Description
Optional. A callback to notify fields after submission has completed successfully.
#### Type
`() => void`
### `allowNull`
#### Description
Optional. Defaults to `false`. By default, if your value is `null`, [``](../api/Field) will convert it to `''`, to ensure [controlled inputs](https://reactjs.org/docs/forms.html#controlled-components). But if you pass `true` to `allowNull`, [``](..api/Field) will give you a `null` value.
#### Type
`boolean`
### `beforeSubmit`
#### Description
Optional. A function to call just before calling `onSubmit`. If `beforeSubmit` returns `false`, the submission will be aborted. If one of your fields returns `false` on `beforeSubmit`, other fields may not have their `beforeSubmit` called, as the submission is aborted on the first one that returns `false`.
#### Type
`() => void | false`
### `children`
#### Description
Optional. (if you specify [`component`](#component) or [`render`](#render)) A render function that is given [`FieldRenderProps`](FieldRenderProps), as well as any non-API props passed into the `` component. For example, if you did...
```tsx
{props => {
console.log(props.someArbitraryOtherProp) // would print 42
return
}}
```
Note that if you specify [`render`](#render) or [`component`](#component) _and_ `children`, `render` will be called, with `children` injected as if it were an additional prop. This can be especially useful for doing something like:
```tsx
```
Related: [`FieldRenderProps`](FieldRenderProps)
#### Type
`((props: FieldRenderProps) => React.Node) | React.Node`
### `component`
#### Description
Optional. If you are not using `'input'`, `'select`' or `'textarea'`, it is recommended that you use [`children`](#children) or [`render`](#render). Either the `string` name of one of the default HTML inputs, or a component that is given [`FieldRenderProps`](FieldRenderProps) as props, children and render props, as well as any non-API props passed into the `` component. For example, if you did...
```tsx
const MyFieldComp = props => {
console.log(props.someArbitraryOtherProp) // would print 42
return
}
```
Related: [`FieldRenderProps`](FieldRenderProps)
#### Type
`React.ComponentType | 'input' | 'select' | 'textarea'`
### `data`
#### Description
Optional. Initial state for arbitrary values to be placed by mutators.
#### Type
`Object`
### `defaultValue`
#### Description
Optional. ⚠️ You probably want [`initialValue`](#initialvalue)! ⚠️ The value of the field upon creation. _**This value is only needed if you want your field be `dirty` upon creation (i.e. for its value to be different from its initial value).**_
#### Type
`any`
### `format`
#### Description
Optional. A function that takes the value from the form values and the name of the field and formats the value to give to the input. Common use cases include converting javascript `Date` values into a localized date string. Almost always used in conjunction with [`parse`](#parse). **Note: If you would like to disable the default behavior of converting `undefined` to `''`, you can pass an [identity function](https://en.wikipedia.org/wiki/Identity_function), `v => v`, to `format`. If you do this, making sure your inputs are "controlled" is up to you.**
#### Type
`(value: any, name: string) => any`
### `formatOnBlur`
#### Description
Optional. Defaults to `false`. If `true`, the `format` function will only be called when the field is blurred. If `false`, `format` will be called on every render.
#### Type
`boolean`
### `initialValue`
#### Description
Optional. The initial value for the field. This value will be used to calculate `dirty` and `pristine` by comparing it to the current value of the field. If you want field to be `dirty` upon creation, you can set one value with `initialValue` and set the value of the field with `defaultValue`. The value given here will override any `initialValues` given to the entire form.
#### Type
`any`
### `isEqual`
#### Description
Optional. Defaults to `===`. A function to determine if two values are equal.
#### Type
`(a: any, b: any) => boolean`
### `multiple`
#### Description
Optional. Only of use when using `component="select"` and you want a multiselect. It will be added on your input component, or you may retrieve its value inside the "input" property of your custom components.
#### Type
`boolean`
```
--------------------------------
### FormSpy onChange Callback
Source: https://github.com/final-form/react-final-form/blob/main/docs/types/FormSpyProps.md
Implement an `onChange` callback to listen for form state changes. When provided, FormSpy will not render anything.
```typescript
(formState: FormState) => void
```
--------------------------------
### Import useForm hook
Source: https://github.com/final-form/react-final-form/blob/main/docs/api/useForm.md
Import the useForm hook from the react-final-form package.
```ts
import { useForm } from 'react-final-form'
```
--------------------------------
### Migrate Formik to React Final Form
Source: https://github.com/final-form/react-final-form/blob/main/docs/migration/formik.md
A diff showing the necessary changes to migrate a basic form from Formik to React Final Form.
```diff
import React from 'react'
-import { Formik, Form, Field, ErrorMessage } from 'formik'
+import { Form, Field, useField } from 'react-final-form'
+// Obviously this could be reused across your project
+const ErrorMessage = ({ name, component }) => {
+ const {
+ meta: { error, touched }
+ } = useField(name, { subscription: { error: true, touched: true } })
+ return error && touched
+ ? React.createElement(component, null, error)
+ : null
+}
const Basic = () => (
Any place in your app!
- {
let errors = {}
if (!values.email) {
errors.email = 'Required'
} else if (
!/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}$/i.test(values.email)
) {
errors.email = 'Invalid email address'
}
return errors
}}
- onSubmit={(values, { setSubmitting }) => {
+ onSubmit={(values) => {
+ // final-form manages submitting status
+ // for you *if* you return a promise
+ return new Promise(resolve =>
setTimeout(() => {
alert(JSON.stringify(values, null, 2))
- setSubmitting(false)
+ resolve()
}, 400)
+ )
}}
>
- {({ isSubmitting }) => (
-
+
)}
-
+
)
export default Basic
```
--------------------------------
### Integrate Custom Input Component
Source: https://github.com/final-form/react-final-form/blob/main/docs/api/Field.md
Manually pass input props to a custom component, ensuring it accepts value and onChange.
```tsx
import TextField from '@material-ui/core/TextField'
...
{props => (
)}
```
--------------------------------
### useForm() Hook
Source: https://github.com/final-form/react-final-form/blob/main/docs/api/useForm.md
The useForm hook retrieves the FormApi instance from the React context. It must be used within a Form component.
```APIDOC
## useForm()
### Description
The useForm() hook plucks the FormApi out of the React context. It will throw an exception if used outside of a component.
### Usage
```ts
import { useForm } from 'react-final-form'
const MyComponent = () => {
const form = useForm();
// Access FormApi methods here
return null;
}
```
### Returns
- **FormApi** (object) - The FormApi instance containing methods to interact with the form state.
```
--------------------------------
### Field Meta State Properties
Source: https://github.com/final-form/react-final-form/blob/main/docs/types/FieldRenderProps.md
Overview of the boolean properties available in the meta object for tracking field state.
```APIDOC
## Field Meta State Properties
### Description
The meta object provides various boolean flags to track the state of a form field. These properties are optional and depend on the subscription settings.
### Properties
- **submitSucceeded** (boolean) - true if the form has been successfully submitted.
- **submitting** (boolean) - true if the form is currently being submitted asynchronously.
- **touched** (boolean) - true if this field has ever gained and lost focus; useful for displaying error messages.
- **valid** (boolean) - true if this field has no validation or submission errors.
- **validating** (boolean) - true if this field is currently waiting on its asynchronous field-level validation function to resolve.
- **visited** (boolean) - true if this field has ever gained focus.
```
--------------------------------
### Import useField Hook
Source: https://github.com/final-form/react-final-form/blob/main/docs/api/useField.md
Import the hook from the react-final-form package.
```typescript
import { useField } from 'react-final-form'
```
--------------------------------
### data Object
Source: https://github.com/final-form/react-final-form/blob/main/docs/types/FieldProps.md
Initial state for arbitrary values used by mutators.
```ts
Object
```
--------------------------------
### Import useFormState hook
Source: https://github.com/final-form/react-final-form/blob/main/docs/api/useFormState.md
Import the useFormState hook from the react-final-form package.
```ts
import { useFormState } from 'react-final-form'
```
--------------------------------
### format Function
Source: https://github.com/final-form/react-final-form/blob/main/docs/types/FieldProps.md
Transforms the field value for display in the input.
```ts
(value: any, name: string) => any
```
--------------------------------
### FormSpy with Render Prop
Source: https://github.com/final-form/react-final-form/blob/main/docs/types/FormSpyProps.md
Use the `render` prop as a function to render form state and pass through arbitrary props. This function receives FormSpyRenderProps and will not be called if an onChange callback is specified.
```tsx
{
console.log(props.someArbitraryOtherProp) // would print 42
return
{JSON.stringify(props.values, undefined, 2)}
}}
/>
```
--------------------------------
### subscription prop
Source: https://github.com/final-form/react-final-form/blob/main/docs/types/FormProps.md
Defines which parts of the FormState the component should subscribe to for re-renders.
```APIDOC
## subscription
### Description
An object of the parts of FormState to subscribe to. If provided, the will only rerender when those specific parts of form state change.
### Parameters
- **subscription** (Object) - Optional - An object mapping FormState keys to booleans. Defaults to subscribing to all state changes.
```
--------------------------------
### Import Form Component
Source: https://github.com/final-form/react-final-form/blob/main/docs/api/Form.md
Import the Form component from the react-final-form library.
```ts
import { Form } from 'react-final-form'
```
--------------------------------
### Define decorators
Source: https://github.com/final-form/react-final-form/blob/main/docs/types/FormProps.md
An array of decorators applied to the form.
```ts
Decorator[]
```
--------------------------------
### FormSpy with Component Prop
Source: https://github.com/final-form/react-final-form/blob/main/docs/types/FormSpyProps.md
Provide a component to the `component` prop to render form state. This component receives FormSpyRenderProps and any arbitrary props. It will not be called if an onChange callback is specified.
```tsx
const MyFormSpyComp = props => {
console.log(props.someArbitraryOtherProp) // would print 42
return
{JSON.stringify(props.values, undefined, 2)}
}
```
--------------------------------
### Import FormSpy Component
Source: https://github.com/final-form/react-final-form/blob/main/docs/api/FormSpy.md
Import the FormSpy component from the 'react-final-form' library.
```typescript
import { FormSpy } from 'react-final-form'
```
--------------------------------
### Update API usage for form reset
Source: https://github.com/final-form/react-final-form/blob/main/docs/migration/redux-form.md
Access the reset function via the form object provided by the render prop instead of using a standalone reset function.
```diff
import React from 'react'
import { Form, Field } from 'react-final-form'
const MyForm = props => {
return (
)}
)
}
export default reduxForm({
form: 'myForm'
})(MyForm)
```
--------------------------------
### render prop
Source: https://github.com/final-form/react-final-form/blob/main/docs/types/FormProps.md
A render function that provides FormRenderProps and additional custom props to the form component.
```APIDOC
## render
### Description
A render function that is given FormRenderProps, as well as any non-API props passed into the component.
### Parameters
- **props** (FormRenderProps) - Required - The form state and helper methods provided to the render function.
### Request Example
}}
/>
```
--------------------------------
### Render Form State with FormSpy
Source: https://github.com/final-form/react-final-form/blob/main/docs/api/FormSpy.md
Use FormSpy to render form state, such as disabling a button when the form is pristine. It subscribes to 'pristine' state and provides form methods like 'reset'.
```tsx
{props => (
)}
```
--------------------------------
### Define render prop type
Source: https://github.com/final-form/react-final-form/blob/main/docs/types/FormProps.md
The type definition for the render function prop.
```ts
(props: FormRenderProps) => React.Node
```
--------------------------------
### FormRenderProps API
Source: https://github.com/final-form/react-final-form/blob/main/docs/types/FormRenderProps.md
Details the properties available within the FormRenderProps object, which are provided by the `` component.
```APIDOC
## FormRenderProps
These are the props that [``](../api/Form) provides to your render function or component. Keep in mind that the values you receive here are dependent upon which values of [`FormState`](/docs/final-form/types/FormState) you have subscribed to with the [`subscription` prop](FormProps#subscription).
This object contains everything in Final Form's [`FormState`](/docs/final-form/types/FormState) as well as:
## `form`
```ts
FormApi
```
The Final Form [`FormApi`](/docs/final-form/types/FormApi).
## `handleSubmit`
```ts
(?SyntheticEvent) => ?Promise
```
A function intended for you to give directly to the `
```
The function's return type depends on the way the [`onSubmit` function is written](../types/FormProps#onsubmit).
Related:
- [`SyntheticEvent`](https://reactjs.org/docs/events.html)
```
--------------------------------
### Update imports for React Final Form
Source: https://github.com/final-form/react-final-form/blob/main/docs/migration/redux-form.md
Replace the redux-form import with react-final-form.
```diff
import React from 'react'
-import { reduxForm, Field } from 'redux-form'
+import { Form, Field } from 'react-final-form'
```
--------------------------------
### component Prop
Source: https://github.com/final-form/react-final-form/blob/main/docs/types/FieldProps.md
Specifies the component or HTML tag to render for the field.
```ts
React.ComponentType | 'input' | 'select' | 'textarea'`
```
```tsx
const MyFieldComp = props => {
console.log(props.someArbitraryOtherProp) // would print 42
return
}
```
--------------------------------
### Render with Spread Operator
Source: https://github.com/final-form/react-final-form/blob/main/docs/api/Field.md
Use the spread operator to pass input props to a standard HTML input element within a render prop.
```tsx
{props => (
)}
```
--------------------------------
### Full Diff: Migrating from Redux Form to React Final Form
Source: https://github.com/final-form/react-final-form/blob/main/docs/migration/redux-form.md
This diff shows the changes required to migrate a form component from using Redux Form to React Final Form, including updated imports and component structure.
```diff
import React from 'react'
-import { reduxForm, Field } from 'redux-form',
+import { Form, Field } from 'react-final-form'
const MyForm = props => {
- const { handleSubmit, pristine, reset, submitting } = props
return (
+
+ )}
+
)
}
-export default reduxForm({
- form: 'myForm',
- initialValues: {
- firstName: 'Dan'
- },
- onSubmit: values => {
- // send values to the cloud
- },
- validate: values => {
- // do validation here, and return errors object
- }
-})(MyForm)
+export default MyForm
```
--------------------------------
### React Final Form Components
Source: https://github.com/final-form/react-final-form/blob/main/docs/api.md
Components provided by React Final Form for form management and field definition.
```APIDOC
## Components
### ``
**Description**: A component that surrounds your entire form and manages the form state. It can inject form state and functionality, e.g. a `handleSubmit` function for you to pass to your `` and creates a "field". It registers itself with the surrounding `` tag and manages all the state for a particular field, providing input callbacks (e.g. `onBlur`, `onChange`, and `onFocus`) as well as the value of the form and myriad metadata about the state of the field.
### ``
**Description**: _[Advanced Usage]_ A component that can tap into form-wide state from inside your ``. It's primarily only for advanced usage when form renders are being restricted via the `subscription` prop.
```
--------------------------------
### Field Name Parameter
Source: https://github.com/final-form/react-final-form/blob/main/docs/api/useField.md
The required name parameter for the field.
```typescript
string
```
--------------------------------
### Submit form via closure
Source: https://github.com/final-form/react-final-form/blob/main/docs/faq.md
Captures the handleSubmit function from the render prop into an external variable to invoke it from outside the form.
```jsx
let submit
return (
// ❌ Not overwritten closure value
// ✅
}}
/>
)
```
--------------------------------
### Define component prop
Source: https://github.com/final-form/react-final-form/blob/main/docs/types/FormProps.md
A component that receives FormRenderProps as props.
```ts
React.ComponentType
```
```tsx
const MyFormComp = props => {
console.log(props.someArbitraryOtherProp) // would print 42
return
}
```
--------------------------------
### useField Hook Signature
Source: https://github.com/final-form/react-final-form/blob/main/docs/api/useField.md
The function signature for the useField hook.
```typescript
(name: string, config: UseFieldConfig) => FieldRenderProps
```
--------------------------------
### Access form state via render props
Source: https://github.com/final-form/react-final-form/blob/main/docs/migration/redux-form.md
Retrieve form state directly from the render prop instead of receiving it as component props.
```diff
import React from 'react'
import { Form, Field } from 'react-final-form'
const MyForm = props => {
- const { handleSubmit, pristine, reset, submitting } = props
return (
)}
)
}
export default reduxForm({
form: 'myForm'
})(MyForm)
```
--------------------------------
### useFormState Hook
Source: https://github.com/final-form/react-final-form/blob/main/docs/api/useFormState.md
The useFormState hook allows components to access the form state. It accepts optional configuration props and returns the current FormState.
```APIDOC
## useFormState
### Description
A hook that returns the current state of the form. It is used internally by the component.
### Parameters
- **config** (FormSpyProps) - Optional - An object matching the shape of FormSpyProps (excluding render props) to configure state subscription.
### Returns
- **FormState** (Object) - The current state of the form, including values, errors, and submission status.
### Usage Example
```ts
import { useFormState } from 'react-final-form'
const MyComponent = () => {
const { values, submitting } = useFormState()
return
}
```
```
--------------------------------
### Field Component API
Source: https://github.com/final-form/react-final-form/blob/main/docs/api/Field.md
The `` component registers a field with the form, subscribes to its state, and provides field state and callbacks through a render prop. It accepts `FieldProps` and calls the render function with `FieldRenderProps`.
```APIDOC
## Field Component API
### Description
The `` component registers a field with the containing form, subscribes to field state, and injects both field state and callback functions (`onBlur`, `onChange`, `onFocus`) via a render prop. It rerenders when the subscribed field state changes.
### Props
`` accepts [`FieldProps`](../types/FieldProps) and calls the render function with [`FieldRenderProps`](../types/FieldRenderProps).
### Required Props
- `name` (string) - Required - The name of the field, can use dot-and-bracket syntax for deep nesting.
- One of `component`, `render`, or `children` is required.
### Rendering Options
- `component` ('input' | 'select' | 'textarea' | React.ComponentType) - Specifies the component to render for the field.
- `render` (Function) - A function that receives render props and returns a React element.
- `children` (Function) - A function that receives render props and returns a React element. Used as a render prop.
### Render Props (`FieldRenderProps`)
- `input` (object) - Contains field state and callbacks:
- `name` (string) - The name of the input.
- `onBlur` (Function) - Callback for when the input loses focus.
- `onChange` (Function) - Callback for when the input value changes.
- `onFocus` (Function) - Callback for when the input gains focus.
- `value` (any) - The current value of the input.
- `meta` (object) - Contains metadata about the field's state (e.g., `touched`, `error`, `submitting`).
### Basic Usage Example (HTML Input)
```tsx
import { Field } from 'react-final-form'
{props => (
)}
```
### Basic Usage Example (Custom Input)
```tsx
import { Field } from 'react-final-form'
import TextField from '@material-ui/core/TextField'
{props => (
)}
```
### Note on Array Values
For array values (e.g., with a tags-input component), use `value={[...props.input.value]}` to prevent "Invalid prop type of 'string' warning".
```
--------------------------------
### FormApi Type Definition
Source: https://github.com/final-form/react-final-form/blob/main/docs/types/FormRenderProps.md
Represents the underlying Final Form API instance.
```ts
FormApi
```
--------------------------------
### Define initialValuesEqual predicate
Source: https://github.com/final-form/react-final-form/blob/main/docs/types/FormProps.md
A predicate to determine if initialValues have changed, defaulting to shallow equals.
```ts
(Object | undefined, Object | undefined) => boolean
```
--------------------------------
### Submit form via HTML form attribute
Source: https://github.com/final-form/react-final-form/blob/main/docs/faq.md
Uses the standard HTML form attribute on a button to trigger submission for a form with a matching ID.
```jsx
{/* ^^^^^^^^^^^^^ */}
```
--------------------------------
### validateOnBlur prop
Source: https://github.com/final-form/react-final-form/blob/main/docs/types/FormProps.md
Configures whether validation triggers on blur or on change.
```APIDOC
## validateOnBlur
### Description
Determines the timing of validation execution.
### Parameters
- **validateOnBlur** (boolean) - Optional - If true, validation happens on blur. If false, validation happens on change. Defaults to false.
```
--------------------------------
### Refactor Redux Form Decorator to React Final Form
Source: https://github.com/final-form/react-final-form/blob/main/docs/migration/redux-form.md
This diff shows how to replace a `reduxForm` decorator with the custom `reactFinalForm` decorator for refactoring.
```diff
-export default reduxForm({
+export default reactFinalForm({
form: 'myForm',
initialValues: {
firstName: 'Dan'
},
onSubmit: values => {
// send values to the cloud
},
validate: values => {
// do validation here, and return errors object
}
})(MyForm)
```
--------------------------------
### handleSubmit Usage in Form
Source: https://github.com/final-form/react-final-form/blob/main/docs/types/FormRenderProps.md
Pass the handleSubmit function directly to the onSubmit prop of the HTML form element.
```jsx
```
--------------------------------
### Destructuring input props for an input element
Source: https://github.com/final-form/react-final-form/blob/main/docs/types/FieldRenderProps.md
Destructure the input props directly into an HTML input element for easy assignment of attributes and event handlers.
```typescript
import React from 'react'
import { Field } from 'react-final-form'
const MyInput = () => (
{props => (
)}
)
```
--------------------------------
### Execute Callback on Form State Change
Source: https://github.com/final-form/react-final-form/blob/main/docs/api/FormSpy.md
Utilize FormSpy's onChange prop to execute code when specific form state, like 'valid', changes. Note that providing an onChange callback prevents any rendering.
```tsx
{
console.log('Form validity changed to', props.valid)
}}
/>
```
--------------------------------
### handleSubmit Type Definition
Source: https://github.com/final-form/react-final-form/blob/main/docs/types/FormRenderProps.md
The function signature for handling form submissions.
```ts
(?SyntheticEvent) => ?Promise
```
--------------------------------
### FieldRenderProps meta.active type
Source: https://github.com/final-form/react-final-form/blob/main/docs/types/FieldRenderProps.md
Indicates if the field currently has focus. This property is optional and may not be present if not subscribed to.
```typescript
boolean
```
--------------------------------
### Import Field Component
Source: https://github.com/final-form/react-final-form/blob/main/docs/api/Field.md
Import the Field component from the react-final-form package.
```ts
import { Field } from 'react-final-form'
```