rc-form Documentation

repository·master·Indexed 23 days ago

https://github.com/react-component/form

A high-order form component for React and React Native (version 2.4.12) providing robust form state management and validation via async-validator. It features tools for binding input components using getFieldProps and getFieldDecorator, as well as a comprehensive form API for managing field values, validation status, and submission.

Tokens
3.2K
Snippets
4
Records
20
Agent score
82%

What's inside rc-form

  1. Important constraints and tips

    master

    When using rc-form, keep these rules in mind:

    1. No Stateless Components: Do not use stateless function components inside a Form component.
    2. Prop Name Collisions: You cannot use the same prop name as the value of trigger or validateTrigger in getFieldProps. If you need a custom onChange, you must provide it in the options or use getFieldDecorator.
    3. Refs: Do not use the ref prop with getFieldProps. Use getFieldInstance(name) to get the field's React public instance instead.
  2. Basic Usage of rc-form

    master

    To use rc-form, wrap your component with createForm(). This injects a form prop into your component. You can then use getFieldProps to bind input elements to the form state and validateFields to handle form submission and validation.

    Note: If you need to provide a custom onChange handler to an input while using getFieldProps, you must explicitly define it within the options object.

    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 (
          <div>
            <input {...getFieldProps('normal')}/>
            <input {...getFieldProps('required', {
              onChange(){}, // have to write original onChange here if you need
              rules: [{required: true}],
            })}/>
            {(errors = getFieldError('required')) ? errors.join(',') : null}
            <button onClick={this.submit}>submit</button>
          </div>
        );
      }
    }
    
    export createForm()(Form);
  3. Use rc-form with React Native

    master

    In React Native, you can use a pattern where you pre-calculate the decorator in componentWillMount to avoid issues with the component lifecycle. This allows you to wrap your native input components with the form logic.

    import { createForm } from 'rc-form';
    
    class Form extends React.Component {
      componentWillMount() {
        this.requiredDecorator = this.props.form.getFieldDecorator('required', {
          rules: [{required: true}],
        });
      }
    
      submit = () => {
        this.props.form.validateFields((error, value) => {
          console.log(error, value);
        });
      }
    
      render() {
        let errors;
        const { getFieldError } = this.props.form;
        return (
          <div>
            {this.requiredDecorator(
              <input
                onChange={/* can still write your own onChange */}
              />
            )}
            {(errors = getFieldError('required')) ? errors.join(',') : null}
            <button onClick={this.submit}>submit</button>
          </div>
        );
      }
    }
    
    export createForm()(Form);
  4. Bind inputs with getFieldDecorator

    master

    The getFieldDecorator(name, option) method is an alternative to getFieldProps. It returns a function that wraps a React node, allowing you to write custom props (like onChange) directly on the child component.

    <form>
      {getFieldDecorator('name', otherOptions)(<input />)}
    </form>
  5. Manage form data and validation

    master

    The form object provided to your component contains several methods for interacting with form state:

    • validateFields([fieldNames], [options], callback): Validates specified fields and returns (errors, values). options.force can be used to re-validate already validated fields.
    • getFieldsValue([fieldNames]): Returns values for specified fields.
    • getFieldValue(fieldName): Returns the value of a specific field.
    • setFieldsValue(obj): Sets values for multiple fields via a key-value object.
    • setFieldsInitialValue(obj): Sets initial values (useful for resets).
    • resetFields([names]): Resets specified fields or all fields.
    • getFieldError(name): Returns an array of error messages for a field.
    • getFieldsError(names): Returns an object containing errors for multiple fields.
    • isFieldTouched(name): Checks if a user has changed the field value.
  6. Configure createForm options

    master

    The createForm(option) function accepts an options object to configure form behavior. Key options include:

    • validateMessages: Preset messages for async-validator.
    • onFieldsChange: Callback when fields change (useful for Redux).
    • onValuesChange: Callback when values change.
    • mapProps: Transform props passed to the wrapped component.
    • mapPropsToFields: Convert props to form fields (useful for Redux).
    • fieldNameProp: String specifying where to store the name argument of getFieldProps.
    • fieldMetaProp: String specifying where to store metadata.
    • fieldDataProp: String specifying where to store field data.
    • withRef (deprecated): Use wrappedComponentRef instead.
  7. Bind inputs with getFieldProps

    master

    The getFieldProps(name, option) method returns an object of props that can be spread onto an input component. This creates a binding between the input and the form state.

    Options for getFieldProps:

    • valuePropName: The prop name for the component's value (default: 'value'). Use 'checked' for checkboxes.
    • getValueProps: Function to transform field value into component props.
    • getValueFromEvent: Function to extract value from an event (default handles target.value and target.checked).
    • initialValue: Initial value for the field.
    • normalize: Function to normalize values.
    • trigger: Event that triggers data collection (default: 'onChange').
    • validateTrigger: Event that triggers validation (default: 'onChange').
    • rules: Validation rules using async-validator syntax.
    • validateFirst: If true, stops validation on the first error.
    • hidden: If true, ignores the field during validation/getting fields.
    • preserve: If true, preserves value when component unmounts.
  8. Use validateFieldsAndScroll for better UX

    master

    If using createDOMForm, you gain access to validateFieldsAndScroll. This method validates fields and automatically scrolls the browser to the first invalid field.

    Options:

    • container: The HTMLElement to act as the scrollable container (defaults to the first scrollable container found in the document).
  9. Extract value from form events with getValueFromEvent

    master
    The getValueFromEvent utility is used to extract the appropriate value from a DOM event or custom element. It automatically handles checkboxes by returning target.checked instead of target.value, and returns target.value for other input types. If the event object or target is missing, it returns the input itself.
  10. Normalize validation rules with normalizeValidateRules

    master
    The normalizeValidateRules function standardizes the structure of validation rules. It ensures that every rule item has a trigger property, which is converted into an array if it was provided as a single string. It also allows merging a set of general rules with a specific validateTrigger into the existing validation array.
  11. Retrieve error messages with getErrorStrs

    master
    The getErrorStrs utility processes an array of error objects and returns an array of strings. If an error object contains a message property, that property is used; otherwise, the error object itself is returned in the resulting array.