### Development Commands for rc-form Source: https://github.com/react-component/form/blob/master/README.md Provides the necessary npm commands to set up the development environment for `rc-form`. This includes installing dependencies and starting a local development server to view examples. ```bash npm install npm start open http://localhost:8000/examples/ ``` -------------------------------- ### React Form Component with FormShape PropTypes Validation Source: https://context7.com/react-component/form/llms.txt This snippet demonstrates how to use formShape for prop validation in a React form component. It shows the import of necessary components from 'rc-form' and 'prop-types', defines a component with static propTypes including formShape.isRequired, and uses getFieldDecorator for input binding. The example also includes form submission handling and integration with the createForm HOC. ```javascript import { createForm, formShape } from 'rc-form'; import React from 'react'; import PropTypes from 'prop-types'; // Using formShape for prop validation class MyFormComponent extends React.Component { static propTypes = { form: formShape.isRequired, onSubmit: PropTypes.func, }; static defaultProps = { onSubmit: () => {}, }; handleSubmit = (e) => { e.preventDefault(); this.props.form.validateFields((err, values) => { if (!err) { this.props.onSubmit(values); } }); }; render() { const { getFieldDecorator } = this.props.form; return (
{getFieldDecorator('field')()}
); } } // formShape validates that form prop has all required methods: // - getFieldsValue, getFieldValue, getFieldInstance // - setFieldsValue, setFields, setFieldsInitialValue // - getFieldDecorator, getFieldProps // - getFieldsError, getFieldError // - isFieldValidating, isFieldsValidating // - isFieldsTouched, isFieldTouched // - isSubmitting, submit // - validateFields, resetFields const EnhancedForm = createForm()(MyFormComponent); // Usage const App = () => ( console.log('Submitted:', values)} /> ); export default App; ``` -------------------------------- ### Retrieve Form Field Values in React using rc-form Source: https://context7.com/react-component/form/llms.txt Explains how to get form field values using `getFieldsValue` and `getFieldValue`. `getFieldsValue` can retrieve all form values or a subset based on provided field names, while `getFieldValue` retrieves the value of a single specified field. These methods are essential for accessing and processing form data. ```javascript import { createForm, formShape } from 'rc-form'; import React from 'react'; class OrderForm extends React.Component { static propTypes = { form: formShape, }; showCurrentValues = () => { // Get all field values const allValues = this.props.form.getFieldsValue(); console.log('All values:', allValues); // { product: 'laptop', quantity: '2', notes: 'urgent' } // Get specific field values const productInfo = this.props.form.getFieldsValue(['product', 'quantity']); console.log('Product info:', productInfo); // { product: 'laptop', quantity: '2' } // Get single field value const quantity = this.props.form.getFieldValue('quantity'); console.log('Quantity:', quantity); // '2' }; calculateTotal = () => { const quantity = this.props.form.getFieldValue('quantity') || 0; const price = this.props.form.getFieldValue('price') || 0; return quantity * price; }; render() { const { getFieldProps } = this.props.form; return (
Total: ${this.calculateTotal()}
); } } export default createForm()(OrderForm); ``` -------------------------------- ### Get Field Validation Errors with rc-form Source: https://context7.com/react-component/form/llms.txt Retrieve validation errors for form fields using `getFieldError` for a single field and `getFieldsError` for multiple fields or all fields. These methods return errors as an array of strings for a given field, or an object mapping field names to their error arrays. They are essential for displaying validation feedback to the user. ```javascript import { createForm, formShape } from 'rc-form'; import React from 'react'; class ErrorDisplayForm extends React.Component { static propTypes = { form: formShape, }; showAllErrors = () => { // Get all field errors const allErrors = this.props.form.getFieldsError(); console.log('All errors:', allErrors); // { username: ['Username is required'], email: ['Invalid email format'] } // Get errors for specific fields const criticalErrors = this.props.form.getFieldsError(['username', 'password']); console.log('Critical errors:', criticalErrors); }; render() { const { getFieldDecorator, getFieldError, getFieldsError } = this.props.form; const errors = getFieldsError(); const hasErrors = Object.keys(errors).some(field => errors[field]); return (
{getFieldDecorator('username', { rules: [{ required: true, message: 'Username is required' }], })()} {/* Display single field error */}
{(getFieldError('username') || []).join(', ')}
{getFieldDecorator('email', { rules: [ { required: true, message: 'Email is required' }, { type: 'email', message: 'Invalid email format' }, ], })()}
{(getFieldError('email') || []).join(', ')}
{/* Display error summary */} {hasErrors && (
Please fix the following errors:
    {Object.keys(errors).map(field => errors[field] && errors[field].map((err, i) => (
  • {err}
  • )) )}
)}
); } } export default createForm()(ErrorDisplayForm); ``` -------------------------------- ### Initialize Form with createForm Source: https://context7.com/react-component/form/llms.txt The createForm factory function enhances a React component with form management capabilities. It supports validation rules, initial values, and callbacks for field or value changes. ```javascript import { createForm, formShape } from 'rc-form'; import React from 'react'; class MyForm extends React.Component { static propTypes = { form: formShape, }; handleSubmit = (e) => { e.preventDefault(); this.props.form.validateFields((error, values) => { if (!error) { console.log('Form submitted successfully:', values); } else { console.log('Validation errors:', error); } }); }; render() { const { getFieldProps, getFieldError } = this.props.form; return (
{(getFieldError('username') || []).join(', ')}
); } } const EnhancedForm = createForm({ validateMessages: { required: (field) => `${field} is required`, }, onFieldsChange(props, changedFields, allFields) { console.log('Fields changed:', changedFields); }, onValuesChange(props, changedValues, allValues) { console.log('Values changed:', changedValues); }, })(MyForm); export default EnhancedForm; ``` -------------------------------- ### Run project test and coverage scripts Source: https://github.com/react-component/form/blob/master/README.md Commands for executing the test suite and generating code coverage reports for the rc-form project. ```bash npm test npm run chrome-test ``` ```bash npm run coverage ``` -------------------------------- ### Basic Form Usage with rc-form (React) Source: https://github.com/react-component/form/blob/master/README.md Demonstrates how to use `rc-form` to create a form with input fields, validation rules, and a submit handler. It utilizes `createForm` to HOC wrap the component and `getFieldProps` to bind form elements. Dependencies include `react` and `rc-form`. ```javascript import { createForm, formShape } from 'rc-form'; class Form extends React.Component { static propTypes = { form: formShape, }; submit = () => { this.props.form.validateFields((error, value) => { console.log(error, value); }); } render() { let errors; const { getFieldProps, getFieldError } = this.props.form; return (
{(errors = getFieldError('required')) ? errors.join(',') : null}
); } } export createForm()(Form); ``` -------------------------------- ### Wrap field data using createFormField Source: https://github.com/react-component/form/blob/master/HISTORY.md Demonstrates the migration from raw object field definitions to using the createFormField helper function required in rc-form version 2.0.0 and later. This ensures proper field data structure for mapPropsToFields. ```jsx import { createForm } from 'rc-form'; createFrom({ mapPropsToFields() { return { name: { value: 'rc-form' }, }; }, }) ``` ```jsx import { createForm, createFormField } from 'rc-form'; createFrom({ mapPropsToFields() { return { name: createFormField({ value: 'rc-form' }), }; }, }) ``` -------------------------------- ### Initialize DOM Form with createDOMForm Source: https://context7.com/react-component/form/llms.txt createDOMForm extends standard form capabilities by adding validateFieldsAndScroll, which automatically scrolls the viewport to the first invalid field upon submission. ```javascript import createDOMForm from 'rc-form/lib/createDOMForm'; import { formShape } from 'rc-form'; import React from 'react'; class ContactForm extends React.Component { static propTypes = { form: formShape, }; handleSubmit = (e) => { e.preventDefault(); this.props.form.validateFieldsAndScroll( { scroll: { offsetTop: 20 } }, (error, values) => { if (!error) { console.log('Form is valid:', values); } else { console.log('Please fix the errors above'); } } ); }; render() { const { getFieldProps, getFieldError } = this.props.form; return (
{(getFieldError('name') || []).join(', ')}
); } } const EnhancedContactForm = createDOMForm()(ContactForm); export default EnhancedContactForm; ``` -------------------------------- ### Form Instance Access with createForm Source: https://github.com/react-component/form/blob/master/README.md Demonstrates how to access the form instance using `wrappedComponentRef` (recommended) or the deprecated `withRef` option in `createForm`. `wrappedComponentRef` provides a direct reference to the component instance. ```jsx class Form extends React.Component { ... } // deprecated const EnhancedForm = createForm({ withRef: true })(Form); // this.refs.form.refs.wrappedComponent // => The instance of Form // Recommended const EnhancedForm = createForm()(Form); this.formRef = inst} /> // this.formRef // => The instance of Form ``` -------------------------------- ### Implement Nested Form Fields with RC Form Source: https://context7.com/react-component/form/llms.txt This component demonstrates the use of dot notation for nested objects and bracket notation for array-based fields. It includes form validation, submission handling, and programmatic value setting using the rc-form library. ```javascript import { createForm, formShape } from 'rc-form'; import React from 'react'; class NestedFieldsForm extends React.Component { static propTypes = { form: formShape, }; handleSubmit = (e) => { e.preventDefault(); this.props.form.validateFields((err, values) => { if (!err) { console.log('Nested values:', values); } }); }; setAllValues = () => { this.props.form.setFieldsValue({ user: { name: { first: 'Jane', last: 'Smith' }, age: '25', }, addresses: [ { street: '789 Pine', city: 'Chicago' }, { street: '321 Elm', city: 'Boston' }, ], }); }; render() { const { getFieldDecorator, getFieldError } = this.props.form; return (

User Info

{getFieldDecorator('user.name.first', { rules: [{ required: true, message: 'First name required' }], })()}
{(getFieldError('user.name.first') || []).join(', ')}
{getFieldDecorator('user.name.last', { rules: [{ required: true, message: 'Last name required' }], })()} {getFieldDecorator('user.age', { rules: [{ pattern: /^\d+$/, message: 'Age must be a number' }], })()}

Address 1

{getFieldDecorator('addresses[0].street', { rules: [{ required: true }], })()} {getFieldDecorator('addresses[0].city', { rules: [{ required: true }], })()}

Address 2

{getFieldDecorator('addresses[1].street')()} {getFieldDecorator('addresses[1].city')()}
); } } export default createForm({ onFieldsChange(_, changedFields, allFields) { console.log('Changed:', changedFields); }, onValuesChange(_, changedValues, allValues) { console.log('Values changed:', changedValues); }, })(NestedFieldsForm); ``` -------------------------------- ### Binding Input Fields with getFieldProps Source: https://github.com/react-component/form/blob/master/README.md Shows how to use `getFieldProps` to create props for input components, establishing a binding for form data collection. It supports custom value prop names and event triggers. ```jsx
``` -------------------------------- ### Shorthand for Validation Trigger and Rules Source: https://github.com/react-component/form/blob/master/README.md Illustrates a shorthand syntax for configuring validation triggers and rules within `getFieldProps` or `getFieldDecorator`. This simplifies the configuration for common validation scenarios. ```javascript // Shorthand { validateTrigger: 'onBlur', rules: [{required: true}], } // Equivalent verbose configuration { validate: [{ trigger: 'onBlur', rules: [{required: true}], }], } ``` -------------------------------- ### Configure field properties with getFieldProps Source: https://github.com/react-component/form/blob/master/README.md Demonstrates how to bind custom event handlers and references when using getFieldProps. Note that standard ref props are not supported and must be handled via getFieldInstance or function refs. ```javascript ``` ```javascript this.props.form.getFieldInstance('ref') ``` ```javascript ``` -------------------------------- ### Integrate React Forms with Redux using createFormField and mapPropsToFields Source: https://context7.com/react-component/form/llms.txt Illustrates how to use `createFormField` in conjunction with `mapPropsToFields` and `onFieldsChange` within `rc-form`'s `createForm` HOC to achieve two-way data binding between a React form and Redux state. This enables seamless synchronization of form data with external state management. Dependencies include `rc-form`, `react`, `react-redux`, and `redux`. ```javascript import { createForm, createFormField, formShape } from 'rc-form'; import React from 'react'; import { connect } from 'react-redux'; class ReduxForm extends React.Component { static propTypes = { form: formShape, }; handleSubmit = (e) => { e.preventDefault(); this.props.form.validateFields((err, values) => { if (!err) { this.props.dispatch({ type: 'SUBMIT_FORM', payload: values }); } }); }; render() { const { getFieldDecorator, getFieldError } = this.props.form; return (
{getFieldDecorator('username', { rules: [{ required: true }], })()}
{(getFieldError('username') || []).join(', ')}
{getFieldDecorator('email', { rules: [{ type: 'email' }], })()}
{(getFieldError('email') || []).join(', ')}
); } } // Connect to Redux and create form with two-way binding const ConnectedForm = connect( (state) => ({ formData: state.form, }) )( createForm({ // Convert Redux state to form fields mapPropsToFields(props) { return { username: createFormField({ value: props.formData.username, }), email: createFormField({ value: props.formData.email, }), }; }, // Sync form changes back to Redux onFieldsChange(props, changedFields) { props.dispatch({ type: 'UPDATE_FORM_FIELDS', payload: changedFields, }); }, })(ReduxForm) ); export default ConnectedForm; ``` -------------------------------- ### Validate Form Fields with Callbacks and Promises in React Source: https://context7.com/react-component/form/llms.txt Demonstrates how to validate specific form fields or all fields using `validateFields`. It supports both callback-style and Promise-based validation, and allows forcing revalidation of fields. This method is crucial for ensuring data integrity before form submission. ```javascript import { createForm, formShape } from 'rc-form'; import React from 'react'; class MultiStepForm extends React.Component { static propTypes = { form: formShape, }; // Validate specific fields only validateStep1 = () => { this.props.form.validateFields(['firstName', 'lastName'], (errors, values) => { if (!errors) { console.log('Step 1 valid:', values); // { firstName: 'John', lastName: 'Doe' } } }); }; // Force revalidation even if field hasn't changed forceValidate = () => { this.props.form.validateFields(['email'], { force: true }, (errors, values) => { console.log('Forced validation result:', errors, values); }); }; // Promise-based validation submitForm = async () => { try { const values = await this.props.form.validateFields(); console.log('All fields valid:', values); // Submit to server } catch ({ errors, values }) { console.log('Validation failed:', errors); console.log('Current values:', values); } }; render() { const { getFieldDecorator } = this.props.form; return (
{getFieldDecorator('firstName', { rules: [{ required: true }], })()} {getFieldDecorator('lastName', { rules: [{ required: true }], })()} {getFieldDecorator('email', { rules: [{ required: true, type: 'email' }], })()}
); } } export default createForm()(MultiStepForm); ``` -------------------------------- ### Set Form Field Values Programmatically in React Source: https://context7.com/react-component/form/llms.txt Demonstrates how to use `setFieldsValue` to programmatically set values for single, multiple, or nested form fields. This function requires fields to be registered with `getFieldProps` or `getFieldDecorator`. It's useful for pre-filling forms or updating field states based on user actions or data fetching. ```javascript import { createForm, formShape } from 'rc-form'; import React from 'react'; class ProfileForm extends React.Component { static propTypes = { form: formShape, }; loadUserData = () => { // Simulate API call const userData = { name: 'John Doe', email: 'john@example.com', bio: 'Software developer', }; // Set multiple field values at once this.props.form.setFieldsValue(userData); }; clearEmail = () => { // Set single field value this.props.form.setFieldsValue({ email: '' }); }; setNestedValues = () => { // Set nested field values this.props.form.setFieldsValue({ address: { street: '123 Main St', city: 'New York', }, }); }; render() { const { getFieldDecorator } = this.props.form; return (
{getFieldDecorator('name', { initialValue: '' })( )} {getFieldDecorator('email', { initialValue: '' })( )} {getFieldDecorator('bio', { initialValue: '' })(