Formily Migration Guide
This skill should be used when the user asks to "convert to formily", "formily migration", "migrate forms to formily", "convert react forms to formily", "formily vs other form libraries", or "replace existing forms with formily".
What this skill does
# Formily Migration Guide
This skill provides comprehensive guidance for converting existing React forms to Formily. Focus on migration strategies, common patterns, and step-by-step conversion processes for different form libraries and vanilla React forms with TypeScript.
## Migration Overview
### Why Migrate to Formily?
1. **Better TypeScript support** - Type-safe form management
2. **Schema-driven approach** - Declarative form definitions
3. **Improved performance** - Efficient reactivity and minimal re-renders
4. **Powerful validation** - Built-in validation with custom rules
5. **Better developer experience** - Less boilerplate, more maintainability
### Migration Strategies
1. **Incremental migration** - Convert forms one at a time
2. **Parallel development** - Build new forms with Formily while maintaining existing ones
3. **Complete rewrite** - Replace entire form system at once
## From Vanilla React Forms
### Before: Vanilla React Form
```typescript
import React, { useState, FormEvent } from 'react'
interface ContactForm {
name: string
email: string
message: string
}
const VanillaContactForm: React.FC = () => {
const [formData, setFormData] = useState<ContactForm>({
name: '',
email: '',
message: ''
})
const [errors, setErrors] = useState<Partial<ContactForm>>({})
const [isSubmitting, setIsSubmitting] = useState(false)
const handleChange = (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => {
const { name, value } = e.target
setFormData(prev => ({ ...prev, [name]: value }))
// Clear error when user starts typing
if (errors[name as keyof ContactForm]) {
setErrors(prev => ({ ...prev, [name]: '' }))
}
}
const validateForm = (): boolean => {
const newErrors: Partial<ContactForm> = {}
if (!formData.name.trim()) {
newErrors.name = 'Name is required'
}
if (!formData.email.trim()) {
newErrors.email = 'Email is required'
} else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(formData.email)) {
newErrors.email = 'Invalid email format'
}
if (!formData.message.trim()) {
newErrors.message = 'Message is required'
}
setErrors(newErrors)
return Object.keys(newErrors).length === 0
}
const handleSubmit = async (e: FormEvent) => {
e.preventDefault()
if (!validateForm()) {
return
}
setIsSubmitting(true)
try {
// Submit form data
await submitForm(formData)
alert('Form submitted successfully!')
setFormData({ name: '', email: '', message: '' })
} catch (error) {
console.error('Submission error:', error)
alert('Submission failed. Please try again.')
} finally {
setIsSubmitting(false)
}
}
return (
<form onSubmit={handleSubmit}>
<div>
<label>Name:</label>
<input
type="text"
name="name"
value={formData.name}
onChange={handleChange}
/>
{errors.name && <span className="error">{errors.name}</span>}
</div>
<div>
<label>Email:</label>
<input
type="email"
name="email"
value={formData.email}
onChange={handleChange}
/>
{errors.email && <span className="error">{errors.email}</span>}
</div>
<div>
<label>Message:</label>
<textarea
name="message"
value={formData.message}
onChange={handleChange}
/>
{errors.message && <span className="error">{errors.message}</span>}
</div>
<button type="submit" disabled={isSubmitting}>
{isSubmitting ? 'Submitting...' : 'Submit'}
</button>
</form>
)
}
```
### After: Formily Version
```typescript
import React from 'react'
import { createForm } from '@formily/core'
import { FormProvider, createSchemaField } from '@formily/react'
import { Form, FormItem, Input, Button } from '@formily/antd'
interface ContactForm {
name: string
email: string
message: string
}
const FormilyContactForm: React.FC = () => {
const form = createForm<ContactForm>({
initialValues: {
name: '',
email: '',
message: ''
},
validateFirst: true
})
const schema = {
type: 'object',
properties: {
name: {
type: 'string',
title: 'Name',
required: true,
'x-decorator': 'FormItem',
'x-component': 'Input',
'x-validator': [
{ required: true, message: 'Name is required' }
]
},
email: {
type: 'string',
title: 'Email',
required: true,
'x-decorator': 'FormItem',
'x-component': 'Input',
'x-validator': [
{ required: true, message: 'Email is required' },
{ format: 'email', message: 'Invalid email format' }
]
},
message: {
type: 'string',
title: 'Message',
required: true,
'x-decorator': 'FormItem',
'x-component': 'Input.TextArea',
'x-validator': [
{ required: true, message: 'Message is required' }
]
}
}
}
const SchemaField = createSchemaField({
components: {
Form,
FormItem,
Input,
Button
}
})
const handleSubmit = async () => {
try {
await form.validate()
const values = form.values
await submitForm(values)
alert('Form submitted successfully!')
form.reset()
} catch (error) {
console.error('Validation errors:', error)
}
}
return (
<FormProvider form={form}>
<Form labelCol={6} wrapperCol={16}>
<SchemaField schema={schema} />
<FormItem wrapperCol={{ offset: 6, span: 16 }}>
<Button type="primary" onClick={handleSubmit}>
Submit
</Button>
</FormItem>
</Form>
</FormProvider>
)
}
```
## From Formik
### Before: Formik Form
```typescript
import React from 'react'
import { Formik, Form, Field, ErrorMessage } from 'formik'
import * as Yup from 'yup'
const FormikExample: React.FC = () => {
const initialValues = {
firstName: '',
lastName: '',
email: '',
age: ''
}
const validationSchema = Yup.object({
firstName: Yup.string().required('First name is required'),
lastName: Yup.string().required('Last name is required'),
email: Yup.string().email('Invalid email').required('Email is required'),
age: Yup.number().min(18, 'Must be at least 18').required('Age is required')
})
const handleSubmit = (values: any, { setSubmitting }: any) => {
submitForm(values)
setSubmitting(false)
}
return (
<Formik
initialValues={initialValues}
validationSchema={validationSchema}
onSubmit={handleSubmit}
>
{({ isSubmitting }) => (
<Form>
<div>
<label>First Name</label>
<Field name="firstName" type="text" />
<ErrorMessage name="firstName" component="div" />
</div>
<div>
<label>Last Name</label>
<Field name="lastName" type="text" />
<ErrorMessage name="lastName" component="div" />
</div>
<div>
<label>Email</label>
<Field name="email" type="email" />
<ErrorMessage name="email" component="div" />
</div>
<div>
<label>Age</label>
<Field name="age" type="number" />
<ErrorMessage name="age" component="div" />
</div>
<button type="submit" disabled={isSubmitting}>
Submit
</button>
</Form>
)}
</Formik>
)
}
```
### After: Formily Version
```typescript
import React from 'react'
import { createForm } from '@formily/core'
import { FormProvider, createSchemaField } from '@formily/react'
import { Form, FormItem, Input, InputNumber, Button } from '@formily/antd'
const FormilyFormikExample: React.FC = () => {
const fRelated in Web Dev
generating-lwc-components
IncludedLightning Web Components with PICKLES methodology and 165-point scoring. Use this skill when the user creates or edits LWC components, builds wire service patterns, or writes Jest tests for LWC. TRIGGER when: user creates/edits LWC components, touches lwc/**/*.js, .html, .css, .js-meta.xml files, or asks about wire service, SLDS, or Jest LWC tests. DO NOT TRIGGER when: Apex classes (use generating-apex), Aura components, or Visualforce.
tanstack-query
IncludedManage server state in React with TanStack Query v5. Set up queries with useQuery, mutations with useMutation, configure QueryClient caching strategies, implement optimistic updates, and handle infinite scroll with useInfiniteQuery. Use when: setting up data fetching in React projects, migrating from v4 to v5, or fixing object syntax required errors, query callbacks removed issues, cacheTime renamed to gcTime, isPending vs isLoading confusion, keepPreviousData removed problems.
document-processor-api
IncludedProcess documents with Nutrient DWS. Use when the user wants to generate PDFs from HTML or URLs, convert Office/images/PDFs, assemble or split packets, OCR scans, extract text/tables/key-value pairs, redact PII, watermark, sign, fill forms, optimize PDFs, or produce compliance outputs like PDF/A or PDF/UA. Triggers include convert to PDF, merge these PDFs, OCR this scan, extract tables, redact PII, sign this PDF, make this PDF/A, or linearize for web delivery.
nutrient-document-processing
IncludedProcess documents with Nutrient DWS. Use when the user wants to generate PDFs from HTML or URLs, convert Office/images/PDFs, assemble or split packets, OCR scans, extract text/tables/key-value pairs, redact PII, watermark, sign, fill forms, optimize PDFs, or produce compliance outputs like PDF/A or PDF/UA. Triggers include convert to PDF, merge these PDFs, OCR this scan, extract tables, redact PII, sign this PDF, make this PDF/A, or linearize for web delivery.
tanstack-query
IncludedManage server state in React with TanStack Query v5. Covers useMutationState, simplified optimistic updates, throwOnError, network mode (offline/PWA), and infiniteQueryOptions. Use when setting up data fetching, fixing v4→v5 migration errors (object syntax, gcTime, isPending, keepPreviousData), or debugging SSR/hydration issues with streaming server components.
accelint-nextjs-best-practices
IncludedNext.js performance optimization and best practices. Use when writing Next.js code (App Router or Pages Router); implementing Server Components, Server Actions, or API routes; optimizing RSC serialization, data fetching, or server-side rendering; reviewing Next.js code for performance issues; fixing authentication in Server Actions; or implementing Suspense boundaries, parallel data fetching, or request deduplication.