craft-formbuilder
v1.1.15
Published
`craft-formbuilder` is a dynamic form-building library that provides components to create and manage form workflows efficiently. Built for React and powered by Redux, `craft-formbuilder` allows you to build highly customizable and scalable forms, ideal fo
Readme
craft-formbuilder
craft-formbuilder is a dynamic form-building library that provides components to create and manage form workflows efficiently. Built for React and powered by Redux, craft-formbuilder allows you to build highly customizable and scalable forms, ideal for use cases in fintech, loan applications, and beyond.
Features
- Dynamic Forms: Easily create dynamic forms using JSON configurations.
- Repeatable Sections: Support for repeatable sections, allowing you to add multiple blocks of fields like "Shareholder" or "Applicant" entries.
- Conditional Logic: Implement dynamic field visibility and validation rules based on form inputs.
- Redux Integration: Leverage Redux Toolkit for centralized form state management, making it easy to integrate with larger applications.
- Field Dependencies: Define dependencies between fields for scenarios like dropdown value changes based on other fields.
- API Lookups: Auto-fetch and populate form fields from API responses using the
fetchOnFillfeature (e.g., fetch customer details on ID blur). - Custom Stepper: Seamlessly incorporate custom steppers for multi-stage forms to improve user navigation.
- External Form Submission: Trigger form submission externally using a reference to the
DynamicFormcomponent.
Installation
Install the package using npm or yarn:
npm install craft-formbuilderor
yarn add craft-formbuilderUsage
Here's a basic example of how to use DynamicForm from craft-formbuilder:
import React from "react";
import { DynamicForm } from "craft-formbuilder";
const formDefinition = {
fields: [
{
name: "business_name",
type: "text",
label: "Business Name",
required: true,
},
{
name: "applicant_name",
type: "text",
label: "Applicant Name",
required: true,
},
{
name: "loan_type",
type: "dropdown",
label: "Loan Type",
options: [
{ label: "Home Loan", value: "home" },
{ label: "Car Loan", value: "car" },
],
},
],
};
const App = () => {
return <DynamicForm formDefinition={formDefinition} />;
};
export default App;Advanced Usage
Handling Form Submission
You can use the exported handleDynamicFormSubmit to handle form submissions outside of the DynamicForm component:
import React from "react";
import { DynamicForm, handleDynamicFormSubmit } from "craft-formbuilder";
import { useDispatch } from "react-redux";
const App = () => {
const dispatch = useDispatch();
const onSubmit = () => {
dispatch(handleDynamicFormSubmit()).then((data) => {
// Handle form submission data here
console.log(data);
});
};
return (
<>
<DynamicForm formDefinition={formDefinition} />
<button onClick={onSubmit}>Submit</button>
</>
);
};
export default App;External Form Submission with Ref
You can also trigger form submission externally using a reference to the DynamicForm component:
import React, { useRef, useState } from "react";
import { Provider, DynamicForm, AxiosProvider } from "craft-formbuilder";
const formJson = {
sections: [
{
title: "Pokemon Information",
fields: [
{
name: "primary.pokemon.name",
label: "Pokemon Name",
fieldType: "text",
validation: {
required: true,
},
},
{
name: "primary.pokemon.type",
label: "Pokemon Type",
fieldType: "dropdown",
source: {
api: "https://pokeapi.co/api/v2/pokemon?offset=20&limit=20",
labelKey: "name",
valueKey: "name",
},
validation: {
required: true,
},
},
],
},
],
};
const App = () => {
const dynamicFormRef = useRef(null);
const [submittedData, setSubmittedData] = useState(null);
const handleFormSubmitSuccess = (data) => {
console.log("Form submitted successfully with data:", data);
setSubmittedData(data);
};
const triggerFormSubmit = () => {
if (dynamicFormRef.current) {
dynamicFormRef.current.submitFormExternally();
}
};
return (
<Provider>
<div>
<h1>Using Craft Formbuilder Library</h1>
<AxiosProvider axiosInstance={axiosInstance}>
<DynamicForm
ref={dynamicFormRef}
componentName="TestForm"
formJson={formJson}
onSubmitSuccess={handleFormSubmitSuccess}
/>
</AxiosProvider>
<button onClick={triggerFormSubmit}>Submit Form Externally</button>
{submittedData && <pre>{JSON.stringify(submittedData, null, 2)}</pre>}
</div>
</Provider>
);
};
export default App;Dynamic Sections
The craft-formbuilder library allows for adding new sections dynamically using repeatable fields. For example, adding multiple "Co-Applicants" or "Guarantors" can be easily managed through the repeatable configuration.
{
"name": "co_applicant",
"type": "section",
"repeatable": true,
"fields": [
{ "name": "name", "type": "text", "label": "Co-Applicant Name" },
{
"name": "relationship",
"type": "dropdown",
"label": "Relationship",
"options": [
{ "label": "Spouse", "value": "spouse" },
{ "label": "Sibling", "value": "sibling" }
]
}
]
}Fetch On Fill (API Lookup)
The fetchOnFill feature allows you to automatically call an API when a field loses focus (onBlur) and populate other form fields with the API response data.
Use Case
When users fill in a field like a customer ID, automatically fetch and populate related information (name, address, credit limit) from your backend API.
GET Request Example
{
"sections": [
{
"title": "Customer Lookup",
"fields": [
{
"name": "customer_id",
"label": "Customer ID",
"fieldType": "text",
"fetchOnFill": {
"api": "/api/customers/{{customer_id}}",
"method": "GET",
"mappings": [
{ "sourceKey": "name", "targetField": "customer_name" },
{ "sourceKey": "address", "targetField": "customer_address" },
{ "sourceKey": "phone", "targetField": "customer_phone" }
]
}
},
{
"name": "customer_name",
"label": "Customer Name",
"fieldType": "text"
},
{
"name": "customer_address",
"label": "Address",
"fieldType": "text"
},
{
"name": "customer_phone",
"label": "Phone",
"fieldType": "text"
}
]
}
]
}POST Request Example
For POST requests, you can specify which fields to include in the request body:
{
"sections": [
{
"title": "Loan Details",
"fields": [
{
"name": "customer_id",
"label": "Customer ID",
"fieldType": "text"
},
{
"name": "branch_code",
"label": "Branch Code",
"fieldType": "text"
},
{
"name": "loan_type",
"label": "Loan Type",
"fieldType": "dropdown",
"fetchOnFill": {
"api": "/api/calculate-limit",
"method": "POST",
"bodyFields": ["customer_id", "branch_code"],
"mappings": [
{ "sourceKey": "maxLimit", "targetField": "max_loan_amount", "dataType": "int" },
{ "sourceKey": "rate", "targetField": "interest_rate", "dataType": "string" }
]
}
},
{
"name": "max_loan_amount",
"label": "Maximum Loan Amount",
"fieldType": "amount"
},
{
"name": "interest_rate",
"label": "Interest Rate (%)",
"fieldType": "decimal"
}
]
}
]
}FetchOnFill Configuration
api(required): URL endpoint with optional{{fieldName}}placeholders. Placeholders are replaced with current field values at runtime.method(optional):'GET'(default) or'POST'bodyFields(optional, POST only): Array of field names to include in the request body. If omitted, all form values are sent.keyMapping(optional, POST only): Object mapping form field names to API parameter names. Allows renaming fields in the POST body.- Example:
{ "customer_id": "customerId", "branch_code": "branchCode" }
- Example:
mappings(required): Array of objects that map API response keys to form fields:sourceKey: The key in the API response objecttargetField: The form field name to populatedataType(optional): Type conversion for the value ('int','string')
Key Mapping Example (Custom Parameter Names)
If your API expects different parameter names than your form fields, use keyMapping:
{
"sections": [
{
"title": "Account Verification",
"fields": [
{
"name": "account_number",
"label": "Account Number",
"fieldType": "text",
"fetchOnFill": {
"api": "/api/verify-account",
"method": "POST",
"bodyFields": ["account_number", "account_type"],
"keyMapping": {
"account_number": "accountNum",
"account_type": "accType"
},
"mappings": [
{ "sourceKey": "accountHolder", "targetField": "account_holder" },
{ "sourceKey": "balance", "targetField": "account_balance", "dataType": "int" }
]
}
},
{
"name": "account_type",
"label": "Account Type",
"fieldType": "dropdown",
"options": [
{ "label": "Savings", "value": "savings" },
{ "label": "Current", "value": "current" }
]
},
{
"name": "account_holder",
"label": "Account Holder",
"fieldType": "text"
},
{
"name": "account_balance",
"label": "Balance",
"fieldType": "amount"
}
]
}
]
}Form values sent:
{
"account_number": "ACC123456",
"account_type": "savings"
}API receives (with keyMapping applied):
{
"accountNum": "ACC123456",
"accType": "savings"
}Behavior
- When a field with
fetchOnFillconfig loses focus (onBlur), the API is called - URL placeholders like
{{customer_id}}are replaced with current form values - For POST requests, the body contains the fields listed in
bodyFields(or all values if not specified) - The API response is mapped to target fields using the
mappingsconfiguration - Duplicate API calls are prevented while a request is pending
- Target field values are automatically updated in the form state
Supported Field Types
The fetchOnFill feature works with all field types:
- Text fields (text, mobile, password)
- Numeric fields (decimal, amount)
- Special fields (textarea, text-auto-complete)
- Date fields (date-picker, month)
API Reference
DynamicForm: The core form component that takesformDefinitionorformJsonas a prop.handleDynamicFormSubmit: Redux action to handle form submission.fetchDynamicFormData: Redux asyncThunk to load form data dynamically.submitFormExternally: Method to trigger form submission from outside the component using a reference.
Props for DynamicForm
formDefinitionorformJson: JSON object defining the form fields and their configurations.onSubmit(optional): Callback to handle form submission when a submit button is clicked.onSubmitSuccess(optional): Callback to handle successful form submission.readonly(optional): Whentrue, all form fields are disabled and Add/Delete buttons in repeatable sections are hidden. Defaults tofalse.
Read-Only Form
Use the readonly prop to render the form in a non-editable state, useful for previewing submitted data:
<Provider>
<AxiosProvider axiosInstance={axiosInstance}>
<DynamicForm
ref={dynamicFormRef}
componentName="TestForm"
formJson={formJson}
existingObject={submittedData}
readonly={true}
/>
</AxiosProvider>
</Provider>Contributing
Contributions are welcome! Feel free to open issues or submit pull requests.
License
This project is licensed under the MIT License.
Feel free to modify the examples to suit your needs, and let us know how craft-formbuilder helps in building dynamic forms for your projects!
