react-dynamic-form-builder-version
v1.0.0
Published
A flexible, theme-able React form builder with comprehensive validation
Downloads
16
Maintainers
Readme
React Dynamic Form Builder
A powerful, flexible, and theme-able React form builder with comprehensive validation, animations, and TypeScript support.
Features
- 🎨 Multiple Themes - 11+ built-in themes including modern gradients
- 🔧 Dynamic Configuration - JSON-driven form generation
- ✅ Comprehensive Validation - 50+ built-in validation rules
- 🎭 Smooth Animations - Framer Motion powered transitions
- 📱 Responsive Design - Mobile-first approach
- 🎯 TypeScript Support - Full type definitions
- 🔌 Extensible - Custom fields, validators, and themes
- ⚡ Performance Optimized - React.memo and smart re-renders
- 🎪 Form Builder UI - Visual form designer included
- 🌙 Dark Mode Ready - Built-in dark theme support
Installation
npm install react-dynamic-form-builder
# or
yarn add react-dynamic-form-builder
# or
pnpm add react-dynamic-form-builderQuick Start
import React from 'react';
import { DynamicForm, rules } from 'react-dynamic-form-builder';
const formConfig = [
{
name: 'firstName',
label: 'First Name',
type: 'text',
placeholder: 'Enter your first name',
required: true,
rules: [
rules.text.required(),
rules.text.minLength(2),
rules.text.alpha()
]
},
{
name: 'email',
label: 'Email',
type: 'email',
placeholder: 'Enter your email',
required: true,
rules: [
rules.email.required(),
rules.email.validEmail()
]
}
];
function MyForm() {
const handleSubmit = (data) => {
console.log('Form submitted:', data);
};
return (
<DynamicForm
config={formConfig}
onSubmit={handleSubmit}
theme="purple"
validateOnChange
showErrorSummary
/>
);
}
export default MyForm;Components
DynamicForm
The main form component that renders fields based on configuration.
<DynamicForm
config={formConfig}
onSubmit={handleSubmit}
theme="purple"
customStyles={{}}
customColors={{}}
animationConfig={{}}
className=""
disabled={false}
loading={false}
resetOnSubmit={false}
validateOnChange={true}
validateOnBlur={true}
showErrorSummary={false}
errorSummaryPosition="top"
submitButtonText="Submit"
resetButtonText="Reset"
showResetButton={false}
onFieldChange={(name, value, formData) => {}}
onValidationChange={(result) => {}}
initialValues={{}}
/>FormBuilder
Visual form builder component for creating forms dynamically.
import { FormBuilder } from 'react-dynamic-form-builder';
function FormDesigner() {
const handleConfigChange = (config) => {
console.log('New config:', config);
};
return (
<FormBuilder
onConfigChange={handleConfigChange}
initialConfig={[]}
enableThemeSelector={true}
enablePreview={true}
availableFieldTypes={['text', 'email', 'select']}
/>
);
}Field Types
Supported field types with examples:
// Text inputs
{ name: 'username', type: 'text', label: 'Username' }
{ name: 'email', type: 'email', label: 'Email Address' }
{ name: 'password', type: 'password', label: 'Password' }
{ name: 'phone', type: 'tel', label: 'Phone Number' }
{ name: 'website', type: 'url', label: 'Website' }
{ name: 'search', type: 'search', label: 'Search Query' }
// Numeric inputs
{ name: 'age', type: 'number', min: 18, max: 100 }
{ name: 'salary', type: 'range', min: 30000, max: 200000 }
// Date/Time inputs
{ name: 'birthday', type: 'date' }
{ name: 'appointment', type: 'datetime-local' }
{ name: 'meeting', type: 'time' }
{ name: 'month', type: 'month' }
{ name: 'week', type: 'week' }
// Selection inputs
{
name: 'country',
type: 'select',
options: ['USA', 'Canada', 'UK']
}
{
name: 'gender',
type: 'radio',
options: ['Male', 'Female', 'Other']
}
{
name: 'skills',
type: 'checkbox',
options: ['JavaScript', 'React', 'Node.js']
}
// Other inputs
{ name: 'bio', type: 'textarea', rows: 4 }
{ name: 'favoriteColor', type: 'color' }
{ name: 'resume', type: 'file', accept: '.pdf,.doc,.docx' }Validation Rules
Comprehensive validation system with 50+ built-in rules:
import { rules, validationSets } from 'react-dynamic-form-builder';
// Text validation
rules.text.required()
rules.text.minLength(3)
rules.text.maxLength(50)
rules.text.alpha()
rules.text.alphaNumeric()
rules.text.hasUppercase()
rules.text.hasLowercase()
rules.text.hasNumber()
rules.text.hasSpecialChar()
rules.text.noSpaces()
// Email validation
rules.email.required()
rules.email.validEmail()
rules.email.domain(['gmail.com', 'company.com'])
// Password validation
rules.password.required()
rules.password.minLength(8)
rules.password.strongPassword()
rules.password.confirmPassword('password')
// Number validation
rules.number.required()
rules.number.min(0)
rules.number.max(100)
rules.number.integer()
rules.number.positive()
// File validation
rules.file.required()
rules.file.maxSize(5) // MB
rules.file.allowedTypes(['image/jpeg', 'image/png'])
rules.file.imageOnly()
rules.file.documentOnly()
// Custom validation
rules.custom.fieldMatch('confirmPassword')
rules.custom.requiredIf('hasAccount', true)
rules.custom.customFunction((val) => val.includes('@'))
// Pre-built sets
validationSets.basicText
validationSets.strongPassword
validationSets.email
validationSets.phone
validationSets.imageFileThemes
Choose from 11+ built-in themes:
// Basic themes
<DynamicForm theme="purple" />
<DynamicForm theme="green" />
<DynamicForm theme="blue" />
<DynamicForm theme="orange" />
<DynamicForm theme="indigo" />
<DynamicForm theme="red" />
<DynamicForm theme="pink" />
<DynamicForm theme="gray" />
// Modern themes
<DynamicForm theme="cyber" /> // Cyberpunk dark theme
<DynamicForm theme="sunset" /> // Gradient sunset theme
<DynamicForm theme="forest" /> // Nature-inspired theme
// Custom theme
<DynamicForm
theme="custom"
customColors={{
formBg: "bg-custom-50",
buttonBg: "bg-custom-600",
// ... other colors
}}
/>Advanced Features
Conditional Fields
{
name: 'hasAccount',
type: 'radio',
options: ['Yes', 'No'],
rules: [rules.radio.required()]
},
{
name: 'accountEmail',
type: 'email',
rules: [
rules.custom.requiredIf('hasAccount', 'Yes'),
rules.email.validEmail()
]
}Async Validation
{
name: 'username',
type: 'text',
rules: [
{
test: async (value) => {
const response = await fetch(`/api/check-username/${value}`);
return response.ok;
},
message: 'Username is already taken',
async: true
}
]
}Field Dependencies
{
name: 'confirmPassword',
type: 'password',
rules: [
rules.password.required(),
{
test: (value, formData) => value === formData.password,
message: 'Passwords must match'
}
]
}Custom Field Styling
{
name: 'specialField',
type: 'text',
customStyle: {
wrapper: 'col-span-2',
input: 'border-2 border-dashed',
label: 'text-lg font-bold'
}
}Hooks
useFormValidation
import { useFormValidation } from 'react-dynamic-form-builder';
function MyComponent() {
const {
errors,
validateField,
validateForm,
hasErrors,
clearErrors
} = useFormValidation(config);
// Use validation methods
}useTheme
import { useTheme } from 'react-dynamic-form-builder';
function MyComponent() {
const {
mergedStyles,
accentColor,
isDarkTheme
} = useTheme('purple', defaultStyles, colorThemes);
// Use theme values
}Pre-built Form Configurations
Import ready-to-use form configurations:
import {
basicFormConfig,
registrationFormConfig,
contactFormConfig,
surveyFormConfig,
jobApplicationFormConfig
} from 'react-dynamic-form-builder';
<DynamicForm config={registrationFormConfig} />Utilities
Form Utils
import { formUtils, fieldUtils } from 'react-dynamic-form-builder';
// Create initial state
const initialState = formUtils.createInitialState(config);
// Format for submission
const formatted = formUtils.formatFormData(formData, config);
// Serialize to JSON
const json = formUtils.serializeToJSON(formData, config);
// Create form data for file uploads
const formDataObj = formUtils.serializeToFormData(formData, config);
// Field creation helpers
const emailField = fieldUtils.emailField('userEmail', {
required: true,
rules: [rules.email.required(), rules.email.validEmail()]
});TypeScript Support
Full TypeScript definitions included:
import { FormField, ValidationRule, FormTheme } from 'react-dynamic-form-builder';
const config: FormField[] = [
{
name: 'email',
label: 'Email Address',
type: 'email',
required: true,
rules: [
rules.email.required(),
rules.email.validEmail()
]
}
];Browser Support
- Chrome/Edge 88+
- Firefox 78+
- Safari 14+
- Mobile browsers with ES2018 support
Contributing
- Fork the repository
- Create your feature branch (
git checkout -b feature/amazing-feature) - Commit your changes (
git commit -m 'Add amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
License
MIT © [Your Name]
