@netpad/forms
React component library for rendering NetPad forms in your applications. Build sophisticated multi-page wizards, add conditional logic, create computed fields, and integrate with your backendβall with declarative configuration.
Installationβ
npm install @netpad/forms
# or
yarn add @netpad/forms
# or
pnpm add @netpad/forms
Peer Dependenciesβ
The package requires the following peer dependencies:
npm install react react-dom @mui/material @mui/icons-material @emotion/react @emotion/styled
Quick Startβ
import { FormRenderer } from '@netpad/forms';
function MyComponent() {
const formConfig = {
name: 'Contact Form',
fieldConfigs: [
{ path: 'name', label: 'Name', type: 'short_text', included: true, required: true },
{ path: 'email', label: 'Email', type: 'email', included: true, required: true },
{ path: 'message', label: 'Message', type: 'long_text', included: true }
]
};
const handleSubmit = (data) => {
console.log('Form submitted:', data);
};
return (
<FormRenderer
config={formConfig}
onSubmit={handleSubmit}
/>
);
}
Key Featuresβ
- Multi-page wizards with progress tracking
- Conditional logic for dynamic field visibility
- Computed fields with formula evaluation
- Built-in validation with custom error messages
- Nested data structures with dot notation paths
- Customizable theming (colors, fonts, input styles)
- 28+ field types (text, number, date, file upload, and more)
Form Configurationβ
Basic Configurationβ
interface FormConfig {
name: string;
fieldConfigs: FieldConfig[];
multiPageConfig?: MultiPageConfig;
variables?: Variable[];
theme?: FormTheme;
}
Form Modesβ
Forms can operate in different modes:
interface FormRendererProps {
config: FormConfig;
mode?: 'create' | 'edit' | 'view' | 'clone';
documentId?: string;
prefillData?: Record<string, any>;
onSubmit?: (data: FormData) => void | Promise<void>;
onError?: (error: FormError) => void;
theme?: FormTheme;
}
Field Typesβ
The package supports 28+ field types organized by category:
Basic Input Fieldsβ
short_text- Single-line text inputlong_text- Multi-line textareaemail- Email input with validationphone- Phone number inputurl- URL input with validationpassword- Password input (masked)
Numeric Fieldsβ
number- Numeric input with min/max validationslider- Range slider inputrating- Star rating input
Selection Fieldsβ
dropdown- Single-select dropdownmultiple_choice- Radio button groupcheckboxes- Multiple checkbox selectionyes_no- Boolean toggle/checkboxtags- Tag input with autocomplete
Date/Time Fieldsβ
date- Date picker with calendartime- Time pickerdatetime- Combined date and time pickerdate_range- Date range selection
Advanced Fieldsβ
autocomplete- Autocomplete input with suggestionsfile_upload- Single file uploadimage_upload- Image upload with previewsignature- Digital signature padnps- Net Promoter Score (0-10 scale)
Layout Fieldsβ
section-header- Section divider with titledescription- Rich text description blockdivider- Visual dividerspacer- Spacing elementimage- Image display
Data Fieldsβ
lookup- Cross-collection reference with autocompletecomputed- Formula-based calculated fieldnested_object- Nested object structurerepeater- Array of structured items
Multi-Page Formsβ
Create step-by-step wizards with progress indicators:
const config = {
name: 'Employee Onboarding',
multiPageConfig: {
enabled: true,
stepIndicator: 'numbers', // 'dots' | 'numbers' | 'progress' | 'tabs'
pages: [
{ id: 'personal', title: 'Personal Info', type: 'form' },
{ id: 'employment', title: 'Employment', type: 'form' },
{ id: 'review', title: 'Review', type: 'summary' }
]
},
fieldConfigs: [
{ path: 'name', label: 'Name', pageId: 'personal', ... },
{ path: 'department', label: 'Department', pageId: 'employment', ... }
]
};
<FormRenderer config={config} onSubmit={handleSubmit} />
Step Indicator Stylesβ
dots- Simple dot indicatorsnumbers- Numbered steps with titlesprogress- Linear progress bartabs- Clickable tab navigation
Conditional Logicβ
Show or hide fields based on other field values:
const fieldConfig = {
path: 'companyName',
label: 'Company Name',
type: 'short_text',
conditionalLogic: {
action: 'show',
logicType: 'all', // 'all' (AND) | 'any' (OR)
conditions: [
{ field: 'accountType', operator: 'equals', value: 'business' }
]
}
};
Available Operatorsβ
equals/notEquals- Exact value matchingcontains/notContains- Partial text matchinggreaterThan/lessThan- Numeric comparisonsisEmpty/isNotEmpty- Check for valuesisTrue/isFalse- Boolean checks
Computed Fieldsβ
Create fields that automatically calculate their value:
const fieldConfig = {
path: 'total',
label: 'Total',
type: 'number',
computed: {
formula: 'price * quantity',
outputType: 'number'
}
};
Formula Syntaxβ
- Use field paths to reference other fields:
price * quantity - Basic arithmetic:
+,-,*,/ - String concatenation:
firstName + " " + lastName - Parentheses for grouping:
(price * quantity) * (1 - discountRate)
Custom Stylingβ
Customize the appearance of your forms:
import { FormRenderer } from '@netpad/forms';
const customTheme = {
primaryColor: '#007bff',
secondaryColor: '#6c757d',
errorColor: '#dc3545',
successColor: '#28a745',
fontFamily: 'Inter, sans-serif',
borderRadius: '8px',
// ... more theme options
};
<FormRenderer
config={formConfig}
theme={customTheme}
onSubmit={handleSubmit}
/>
API Clientβ
The package includes a client for fetching forms and submitting data:
import { createNetPadClient } from '@netpad/forms';
const client = createNetPadClient({
baseUrl: 'https://your-netpad-instance.com',
apiKey: 'np_live_xxx'
});
// Fetch form configuration
const form = await client.getForm('my-form-id');
// Submit form data
await client.submitForm('my-form-id', formData);
Utility Functionsβ
The package exports utility functions for advanced use cases:
import {
evaluateConditionalLogic,
validateField,
validateForm,
evaluateFormula,
getNestedValue,
setNestedValue
} from '@netpad/forms';
// Evaluate conditional logic
const shouldShow = evaluateConditionalLogic(
field.conditionalLogic,
formData
);
// Validate a field
const errors = validateField(field, value);
// Validate entire form
const formErrors = validateForm(config, formData);
// Evaluate computed field formula
const result = evaluateFormula(field.computed.formula, formData);
// Handle nested data paths
const value = getNestedValue(formData, 'user.address.city');
setNestedValue(formData, 'user.address.city', 'New York');
TypeScript Supportβ
Full TypeScript support with exported types:
import type {
FormConfiguration,
FieldConfig,
FormRendererProps,
FormData,
FormError,
FormTheme,
MultiPageConfig,
Variable
} from '@netpad/forms';
const config: FormConfiguration = {
name: 'My Form',
fieldConfigs: [
// TypeScript will validate field configurations
]
};
Examplesβ
Complete Form with Validationβ
import { FormRenderer } from '@netpad/forms';
function ContactForm() {
const config = {
name: 'Contact Form',
fieldConfigs: [
{
path: 'name',
label: 'Full Name',
type: 'short_text',
included: true,
required: true,
validation: {
minLength: 2,
maxLength: 100
}
},
{
path: 'email',
label: 'Email Address',
type: 'email',
included: true,
required: true
},
{
path: 'message',
label: 'Message',
type: 'long_text',
included: true,
required: true,
validation: {
minLength: 10
}
}
]
};
const handleSubmit = async (data) => {
try {
await fetch('/api/contact', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(data)
});
alert('Thank you for your message!');
} catch (error) {
console.error('Submission error:', error);
}
};
return <FormRenderer config={config} onSubmit={handleSubmit} />;
}
Multi-Page Wizardβ
function OnboardingWizard() {
const config = {
name: 'Employee Onboarding',
multiPageConfig: {
enabled: true,
stepIndicator: 'numbers',
pages: [
{ id: 'personal', title: 'Personal Information', type: 'form' },
{ id: 'employment', title: 'Employment Details', type: 'form' },
{ id: 'review', title: 'Review & Submit', type: 'summary' }
]
},
fieldConfigs: [
// Personal info fields with pageId: 'personal'
// Employment fields with pageId: 'employment'
]
};
return <FormRenderer config={config} onSubmit={handleSubmit} />;
}
API Referenceβ
FormRendererβ
Main component for rendering forms.
Props:
config: FormConfiguration- Form configuration objectmode?: 'create' | 'edit' | 'view' | 'clone'- Form mode (default: 'create')documentId?: string- Document ID for edit/view/clone modesprefillData?: Record<string, any>- Pre-fill form with dataonSubmit?: (data: FormData) => void | Promise<void>- Submit handleronError?: (error: FormError) => void- Error handlertheme?: FormTheme- Custom theme configuration
FormConfigurationβ
Complete form configuration object.
Properties:
name: string- Form namefieldConfigs: FieldConfig[]- Array of field configurationsmultiPageConfig?: MultiPageConfig- Multi-page wizard configurationvariables?: Variable[]- Form variablestheme?: FormTheme- Form theme
FieldConfigβ
Individual field configuration.
Properties:
path: string- Field path (supports dot notation for nested fields)label: string- Field labeltype: FieldType- Field typeincluded: boolean- Whether field is included in formrequired?: boolean- Whether field is requireddefaultValue?: any- Default valueplaceholder?: string- Placeholder textvalidation?: ValidationRules- Validation rulesconditionalLogic?: ConditionalLogic- Conditional visibility rulescomputed?: ComputedField- Computed field configurationpageId?: string- Page ID for multi-page forms
Resourcesβ
- NPM Package: @netpad/forms
- GitHub: github.com/mongodb/netpad
- Examples: Check the
/examples/directory in the repository - Form Builder Guide: Form Builder Documentation
Related Documentationβ
- Developer Packages Overview - All NetPad packages
- Workflows Package - Workflow API client
- MCP Server - AI-powered development tools
- Form Builder Guide - Building forms in NetPad