### Develop rc-field-form Locally Source: https://github.com/react-component/field-form/blob/master/README.md Instructions to set up the development environment for rc-field-form. This involves installing dependencies, starting a local development server, and accessing the application via a provided URL. ```bash npm install npm start open http://localhost:8000 ``` -------------------------------- ### Basic Form Setup with Validation in React Source: https://context7.com/react-component/field-form/llms.txt Demonstrates a simple login form using `rc-field-form`. It includes input fields for username and password, applying required and minimum length validation rules. The `onFinish` and `onFinishFailed` handlers are provided for success and failure scenarios respectively. ```typescript import Form, { Field } from 'rc-field-form'; // Simple form with validation const LoginForm = () => { return (
{ console.log('Form submitted:', values); // values = { username: 'john', password: 'secret123' } }} onFinishFailed={(errorInfo) => { console.log('Validation failed:', errorInfo.errorFields); // errorInfo = { values, errorFields: [{ name: ['username'], errors: ['Username is required'] }], outOfDate: false } }} >
); }; ``` -------------------------------- ### Basic Form Usage in React Source: https://github.com/react-component/field-form/blob/master/README.md A fundamental example demonstrating how to use the `Form` and `Field` components from `rc-field-form` to create a simple login form. It includes input fields for username and password and a submit button, with an `onFinish` handler to log form values. ```javascript import Form, { Field } from 'rc-field-form'; const Input = ({ value = '', ...props }) => ; const Demo = () => { return (
{ console.log('Finish:', values); }} >
); }; export default Demo; ``` -------------------------------- ### Handling Form Submission with Ref in React Source: https://github.com/react-component/field-form/blob/master/README.md Illustrates how to manage focus on an input field after form submission using a ref in React. This example shows a basic form structure with a Field component and an input element attached to a ref. ```jsx
``` -------------------------------- ### FormProvider for Multiple Forms and Validation in React Source: https://context7.com/react-component/field-form/llms.txt This example demonstrates the use of `FormProvider` in rc-field-form to manage multiple independent forms within a single application. It shows how to configure global validation messages, listen for form changes, and access values from different forms during submission, facilitating complex user interfaces and workflows. ```typescript import Form, { Field, FormProvider } from 'rc-field-form'; import React, { useState } from 'react'; const MultiFormsApp = () => { const [form1] = Form.useForm(); const [form2] = Form.useForm(); return ( { console.log('Form changed:', name, info.changedFields); // name = 'loginForm' or 'registerForm' // info = { changedFields: [...], forms: { loginForm: FormInstance, registerForm: FormInstance } } }} onFormFinish={(name, info) => { console.log('Form finished:', name, info.values); if (name === 'loginForm') { // Access other form const registerValues = info.forms.registerForm.getFieldsValue(); console.log('Register form values:', registerValues); } }} >

Login Form

Register Form

); }; ``` -------------------------------- ### Programmatic Form Control with useForm Hook in React Source: https://context7.com/react-component/field-form/llms.txt Illustrates advanced form management using the `useForm` hook from `rc-field-form`. This example shows how to programmatically set form values, validate specific fields, and retrieve form values and errors. It's useful for scenarios requiring external control over form state. ```typescript import Form, { Field } from 'rc-field-form'; import type { FormInstance } from 'rc-field-form'; const AdvancedForm = () => { const [form] = Form.useForm(); const handleFillForm = () => { form.setFieldsValue({ username: 'admin', email: 'admin@example.com' }); }; const handleValidateField = async () => { try { await form.validateFields(['email']); console.log('Email is valid'); } catch (errorInfo) { console.log('Validation errors:', errorInfo); } }; const handleGetValues = () => { const allValues = form.getFieldsValue(); console.log('All values:', allValues); const username = form.getFieldValue('username'); console.log('Username:', username); const errors = form.getFieldError('email'); console.log('Email errors:', errors); // string[] }; return ( <>
console.log(values)}>
); }; ``` -------------------------------- ### Form Component API Source: https://github.com/react-component/field-form/blob/master/README.md Documentation for the `Form` component, detailing its available props for managing form state, handling user input, and controlling validation. ```APIDOC ## Form Component API This section details the props available for the `Form` component in `rc-field-form`. ### Description The `Form` component is the main wrapper for managing form state, handling submissions, and validating fields. It accepts various props to customize its behavior and appearance. ### Method Not Applicable (Component API) ### Endpoint Not Applicable (Component API) ### Parameters #### Props - **component** (string | Component | false) - Customize the render component for the Form. Defaults to 'form'. - **fields** ([FieldData](#fielddata)[]) - Control the status of Form fields. Primarily used when integrating with Redux. - **form** ([FormInstance](#useform)) - Set the form instance created by `useForm`. Defaults to `Form.useForm()`. - **initialValues** (Object) - Set the initial values for the Form fields. - **name** (string) - Configure a name for the Form when used with [FormProvider](#formprovider). - **preserve** (boolean) - Determines whether to preserve field values when a field is removed from the form. Defaults to `false`. - **validateMessages** ([ValidateMessages](#validatemessages)) - Set custom validation message templates. - **onFieldsChange** ((changedFields, allFields) => void) - Callback function triggered when any field's value changes. It receives the changed fields and all current fields as arguments. - **onFinish** ((values) => void) - Callback function triggered when the form is successfully submitted and all validations pass. It receives the form values. - **onFinishFailed** (({ values, errorFields, outOfDate }) => void) - Callback function triggered when the form submission fails due to validation errors or other issues. It receives an object containing values, error fields, and out-of-date status. - **onValuesChange** ((changedValues, values) => void) - Callback function triggered when any field's value changes. It receives the changed values and the complete form values. ### Request Example ```jsx import Form, { Field } from 'rc-field-form'; const Input = ({ value = '', ...props }) => ; const MyForm = () => { return (
console.log('Form submitted:', values)} onFieldsChange={(changedFields, allFields) => { console.log('Field changed:', changedFields, 'All fields:', allFields); }} >
); }; export default MyForm; ``` ### Response #### Success Response (Form Submission) - **values** (Object) - The current values of all form fields upon successful submission. #### Error Response (Form Submission Failure) - **values** (Object) - The form field values at the time of submission failure. - **errorFields** (Array) - An array of objects, where each object represents a field with validation errors. Contains `name`, `errors`, and `touched` properties. - **outOfDate** (boolean) - Indicates if the submission was out of date, potentially due to rapid state changes. #### Response Example (onFinish) ```json { "username": "john_doe", "password": "securepassword123" } ``` #### Response Example (onFinishFailed) ```json { "values": { "username": "", "password": "pass" }, "errorFields": [ { "name": "username", "errors": ["Username is required."], "touched": true } ], "outOfDate": false } ``` ``` -------------------------------- ### Create and Use Form Instance with useForm Hook (React JSX) Source: https://github.com/react-component/field-form/blob/master/README.md Demonstrates how to create a form instance using the `Form.useForm` hook and pass it to the Form component. This allows for direct manipulation and access to form state within functional components. ```jsx const Demo = () => { const [form] = Form.useForm(); return
; }; ``` -------------------------------- ### TypeScript Integration for Type-Safe Forms with rc-field-form Source: https://context7.com/react-component/field-form/llms.txt This code snippet demonstrates how to integrate `rc-field-form` with TypeScript to achieve type safety. It defines an interface for form values, uses `Form.useForm` with a generic type, and shows type-safe ways to handle form submission, manual validation, and retrieving field values. Dependencies include `rc-field-form`. ```typescript import Form, { Field } from 'rc-field-form'; import type { FormInstance } from 'rc-field-form'; // Define form values type interface UserFormValues { username: string; email: string; age: number; address: { city: string; zipCode: string; }; hobbies: string[]; } const TypeSafeForm = () => { const [form] = Form.useForm(); const handleSubmit = (values: UserFormValues) => { // values is fully typed console.log(values.username); // string console.log(values.age); // number console.log(values.address.city); // string console.log(values.hobbies); // string[] }; const handleManualValidation = async () => { try { // Return type is UserFormValues const values = await form.validateFields(); console.log(values.email); // Type-safe access } catch (error) { console.error('Validation failed'); } }; const handleGetValues = () => { // Type-safe field access const username = form.getFieldValue('username'); // any (runtime) const age = form.getFieldValue('age'); // Type-safe full form values const allValues = form.getFieldsValue(); // UserFormValues console.log(allValues.address.city); }; return ( form={form} onFinish={handleSubmit} initialValues={{ username: '', email: '', age: 0, address: { city: '', zipCode: '' }, hobbies: [] }} > {(fields, { add, remove }) => ( <> {fields.map((field) => ( ))} )} ); }; ``` -------------------------------- ### Async Validation with validateFields in Field Form Source: https://github.com/react-component/field-form/blob/master/README.md This code snippet shows how to use async/await with the `validateFields` method in Field Form. It attempts to validate form fields and logs the values upon success or iterates through errors if validation fails. No external dependencies are required beyond the Field Form library itself. The input is form data, and the output is either the validated form values or a list of errors. ```javascript async function() { try { const values = await form.validateFields(); console.log(values); } catch (errorList) { errorList.forEach(({ name, errors }) => { // Do something... }); } } ``` -------------------------------- ### Conditional Fields using shouldUpdate and dependencies in React Source: https://context7.com/react-component/field-form/llms.txt This TypeScript code snippet demonstrates conditional field rendering in a React form using the `rc-field-form` library. It uses `shouldUpdate` to re-render a section of the form when the 'accountType' field changes, displaying relevant fields for 'business' or 'personal' accounts. An alternative approach using the `dependencies` prop is also shown for a 'description' field. ```typescript import Form, { Field } from 'rc-field-form'; import React from 'react'; const ConditionalFieldsForm = () => { const [form] = Form.useForm(); return (
console.log(values)}> {/* Conditional field using shouldUpdate */} prevValues.accountType !== currentValues.accountType}> {() => { const accountType = form.getFieldValue('accountType'); if (accountType === 'business') { return ( <> ); } if (accountType === 'personal') { return ( ); } return null; }} {/* Alternative: Using dependencies prop */} {() => { const accountType = form.getFieldValue('accountType'); if (!accountType) return null; return (