### 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 (
);
}
}
// 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 (
);
}
}
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 (
);
}
}
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 (
);
}
}
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 (
);
}
}
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 (
);
}
}
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 (
);
}
}
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 (
);
}
}
// 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 (
);
}
}
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 (
);
}
}
export default createForm()(ProfileForm);
```
--------------------------------
### Force field revalidation
Source: https://github.com/react-component/form/blob/master/HISTORY.md
Shows how to trigger a revalidation of specific form fields by passing the force option to the validateFields method.
```javascript
this.props.validateFields(['xx'], {force: true});
```
--------------------------------
### Bind form fields using getFieldProps in React
Source: https://context7.com/react-component/form/llms.txt
The getFieldProps method returns an object of props to spread onto input elements, creating a binding between the input and form state. It handles value updates, validation triggers, and error tracking automatically.
```javascript
import { createForm, formShape } from 'rc-form';
import React from 'react';
class RegistrationForm extends React.Component {
static propTypes = {
form: formShape,
};
checkUsernameExists = (rule, value, callback) => {
setTimeout(() => {
if (value === 'admin') {
callback([new Error('Username already exists')]);
} else {
callback();
}
}, 500);
};
render() {
const { getFieldProps, getFieldError, isFieldValidating } = this.props.form;
return (
);
}
}
export default createForm()(RegistrationForm);
```
--------------------------------
### Check Field Validation Status with isFieldValidating and isFieldsValidating in React
Source: https://context7.com/react-component/form/llms.txt
Demonstrates how to use `isFieldValidating` and `isFieldsValidating` from `rc-form` to display loading indicators during asynchronous validation. This is crucial for providing user feedback when operations like API checks are in progress. It requires `rc-form` and React.
```javascript
import { createForm, formShape } from 'rc-form';
import React from 'react';
class AsyncValidationForm extends React.Component {
static propTypes = {
form: formShape,
};
checkUsernameAvailable = (rule, value, callback) => {
if (!value) {
callback();
return;
}
// Simulate async API check
setTimeout(() => {
if (['admin', 'root', 'system'].includes(value.toLowerCase())) {
callback([new Error('Username is reserved')]);
} else {
callback();
}
}, 1500);
};
checkEmailExists = (rule, value, callback) => {
if (!value) {
callback();
return;
}
setTimeout(() => {
if (value.endsWith('@test.com')) {
callback([new Error('Test emails not allowed')]);
} else {
callback();
}
}, 1000);
};
render() {
const {
getFieldDecorator,
getFieldError,
isFieldValidating,
isFieldsValidating
} = this.props.form;
const isValidating = isFieldsValidating();
return (
);
}
}
export default createForm()(AsyncValidationForm);
```
--------------------------------
### Form Usage with Decorator (React)
Source: https://github.com/react-component/form/blob/master/README.md
An alternative method for using `rc-form` with a decorator pattern, simplifying the binding of form fields. This approach uses `getFieldDecorator` to wrap input elements and manage their state and validation. It's suitable for scenarios where direct DOM manipulation is preferred.
```javascript
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 (
);
}
}
export createForm()(Form);
```
--------------------------------
### Reset Form Fields Programmatically in React
Source: https://context7.com/react-component/form/llms.txt
Illustrates how to use `resetFields` to reset form fields to their initial values, clear validation errors, and reset touched state. It can reset all fields at once or specific fields by providing an array of field names. This is commonly used after form submission or when a user wants to clear their input.
```javascript
import { createForm, formShape } from 'rc-form';
import React from 'react';
class ResetableForm extends React.Component {
static propTypes = {
form: formShape,
};
resetAll = () => {
// Reset all fields to initial values
this.props.form.resetFields();
};
resetUsername = () => {
// Reset specific field
this.props.form.resetFields(['username']);
};
resetMultiple = () => {
// Reset multiple specific fields
this.props.form.resetFields(['email', 'phone']);
};
handleSubmit = (e) => {
e.preventDefault();
this.props.form.validateFields((err, values) => {
if (!err) {
console.log('Submitted:', values);
// Reset form after successful submission
this.props.form.resetFields();
}
});
};
render() {
const { getFieldDecorator, getFieldError } = this.props.form;
return (
);
}
}
export default createForm()(ResetableForm);
```
--------------------------------
### Decorating Input Fields with getFieldDecorator
Source: https://github.com/react-component/form/blob/master/README.md
Explains `getFieldDecorator`, a helper function similar to `getFieldProps` that simplifies binding input fields. It allows direct attachment of event handlers like `onChange` within the input's props.
```jsx
```
--------------------------------
### Wrap form elements using getFieldDecorator in React
Source: https://context7.com/react-component/form/llms.txt
The getFieldDecorator function wraps form components to provide a cleaner syntax for binding. It allows developers to maintain form state while keeping the ability to attach event handlers directly to the wrapped component.
```javascript
import { createForm, formShape } from 'rc-form';
import React from 'react';
class LoginForm extends React.Component {
static propTypes = {
form: formShape,
};
componentWillMount() {
this.usernameDecorator = this.props.form.getFieldDecorator('username', {
initialValue: '',
rules: [{ required: true, message: 'Please enter username' }],
});
}
handleUsernameChange = (e) => {
console.log('Username typing:', e.target.value);
};
render() {
return (
);
}
}
export default createForm()(LoginForm);
```
--------------------------------
### Real-time Field Value Transformation with normalize in React
Source: https://context7.com/react-component/form/llms.txt
The 'normalize' option allows for real-time transformation of form field values as they are entered. This can be used for tasks like converting text to uppercase, formatting phone numbers, or ensuring min/max constraints. It takes a function that receives the current value and previous value, returning the transformed value.
```javascript
import { createForm, formShape } from 'rc-form';
import React from 'react';
class NormalizeForm extends React.Component {
static propTypes = {
form: formShape,
};
// Convert to uppercase as user types
toUpperCase = (value, prevValue) => {
if (value === prevValue) return value;
return value ? value.toUpperCase() : value;
};
// Format phone number as (XXX) XXX-XXXX
formatPhone = (value) => {
if (!value) return value;
const digits = value.replace(/\D/g, '').slice(0, 10);
if (digits.length <= 3) return digits;
if (digits.length <= 6) return `(${digits.slice(0, 3)}) ${digits.slice(3)}`;
return `(${digits.slice(0, 3)}) ${digits.slice(3, 6)}-${digits.slice(6)}`;
};
// Keep min <= max
normalizeMin = (value, prevValue, allValues) => {
const max = allValues.max;
if (max && Number(value) > Number(max)) {
return max;
}
return value;
};
normalizeMax = (value, prevValue, allValues) => {
const min = allValues.min;
if (min && Number(value) < Number(min)) {
return min;
}
return value;
};
render() {
const { getFieldProps } = this.props.form;
return (
);
}
}
export default createForm()(NormalizeForm);
```
--------------------------------
### Default getValueFromEvent Function
Source: https://github.com/react-component/form/blob/master/README.md
Provides the default implementation for `getValueFromEvent`, which is used to extract the value from an event object. It handles standard input events and checkbox states.
```javascript
function defaultGetValueFromEvent(e) {
if (!e || !e.target) {
return e;
}
const { target } = e;
return target.type === 'checkbox' ? target.checked : target.value;
}
```
--------------------------------
### Check Field Interaction Status with rc-form
Source: https://context7.com/react-component/form/llms.txt
Determine if form fields have been interacted with using `isFieldTouched` for a single field and `isFieldsTouched` for multiple or all fields. This is useful for conditionally displaying validation messages only after a user has engaged with a form element, improving user experience.
```javascript
import {
createForm,
formShape
} from 'rc-form';
import React from 'react';
class TouchAwareForm extends React.Component {
static propTypes = {
form: formShape,
};
render() {
const {
getFieldDecorator,
getFieldError,
isFieldTouched,
isFieldsTouched
} = this.props.form;
// Only show errors after field has been touched
const usernameError = isFieldTouched('username') && getFieldError('username');
const emailError = isFieldTouched('email') && getFieldError('email');
// Check if any fields have been touched
const formTouched = isFieldsTouched();
const specificFieldsTouched = isFieldsTouched(['username', 'email']);
return (
);
}
}
export default createForm()(TouchAwareForm);
```
--------------------------------
### Preserving Field State with preserve Option in React Forms
Source: https://context7.com/react-component/form/llms.txt
The 'preserve' option in rc-form ensures that a field's value is retained in the form's state even after its corresponding component has been unmounted. This is particularly useful for multi-step forms or when fields are conditionally rendered, preventing data loss when navigating between form sections.
```javascript
import { createForm, formShape } from 'rc-form';
import React from 'react';
class PreserveForm extends React.Component {
static propTypes = {
form: formShape,
};
state = {
showOptional: false,
step: 1,
};
toggleOptional = () => {
this.setState(prev => ({ showOptional: !prev.showOptional }));
};
nextStep = () => {
this.setState({ step: 2 });
};
prevStep = () => {
this.setState({ step: 1 });
};
handleSubmit = (e) => {
e.preventDefault();
this.props.form.validateFields((err, values) => {
if (!err) {
console.log('All values including unmounted fields:', values);
// Values from both steps are preserved
}
});
};
render() {
const { getFieldDecorator } = this.props.form;
const { showOptional, step } = this.state;
return (
);
}
}
export default createForm()(PreserveForm);
```
=== COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.