Skip to content

Commit

Permalink
Merge pull request #35 from bleu-fi/use-custom-components-build-form
Browse files Browse the repository at this point in the history
feat: add API to use custom components in build form
  • Loading branch information
luizakp authored Mar 15, 2024
2 parents 0a93af6 + 3b9994e commit bcf5940
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 3 deletions.
19 changes: 17 additions & 2 deletions src/components/FormBuilder/buildForm.tsx
Original file line number Diff line number Diff line change
@@ -1,15 +1,30 @@
import React from "react";
import { BaseField, CommonFieldProps, fieldComponents } from "./index";

type FieldComponentType = (
props: CommonFieldProps<BaseField>
) => React.ReactNode | null;

// In case you want to use a custom component for a specific field type
// you can pass it as an argument to the buildForm function OR in the 'component' property of the field object.
// The 'component' property will take precedence over the customComponents argument.
// The customComponents argument will take precedence over the default fieldComponents.
// If you have a set of custom components that you want to use for all fields, you can implement a wrapper function around buildForm
// that has the customComponents argument pre-filled.
// e.g. const myBuildForm = (fields, form, index = 0) => buildForm(fields, form, index, LOCAL_COMPONENTS);

export function buildForm(
fields: CommonFieldProps<BaseField>["field"][],
form: CommonFieldProps<BaseField>["form"],
index = 0
index = 0,
customComponents: { [key: string]: FieldComponentType } = {}
) {
// @ts-ignore
const formElements = fields.map((field) => {
// @ts-ignore
const FieldComponent = field?.component || fieldComponents[field.type];
const FieldComponent: FieldComponentType =
field?.component ||
{ ...fieldComponents, ...customComponents }[field.type];
if (!FieldComponent) {
throw new Error(`Invalid field type: ${field.type}`);
}
Expand Down
3 changes: 2 additions & 1 deletion src/components/FormBuilder/fields.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import { TextAreaFieldProps } from "./fields/TextAreaField";
import { FieldArrayFieldProps } from "./fields/FieldArray";

export interface BaseField {
component?: React.ComponentType<CommonFieldProps<BaseField>>;
conditions?: Array<{
name: string;
value: string | Array<string>;
Expand All @@ -26,7 +27,7 @@ export interface BaseField {
placeholder?: string;
required?: boolean;
tooltip?: string;
type?: string;
type: string;
value: string;
// Other common properties...
}
Expand Down

0 comments on commit bcf5940

Please sign in to comment.