React Form Builder 2

repository·master·Indexed 19 days ago

https://github.com/kiho/react-form-builder

A complete React-based form construction tool for visually building forms and saving/loading their structure via JSON endpoints. It includes the ReactFormBuilder for form creation and ReactFormGenerator for rendering the resulting forms for end-users. The library supports a wide range of standard form elements, custom component registration via a Registry, and integration with Bootstrap and FontAwesome.

Tokens
9.4K
Snippets
23
Records
39
Agent score
67%

What's inside react-form-builder2

  1. How read-only signatures work

    master

    Read-only signatures allow you to inject a saved/canned signature (in Base64 format) into a form.

    1. In the form builder, choose the "Read only" option for a signature field.
    2. Enter the key name of the variable that will hold the signature.
    3. Pass the signature data via the variables prop to ReactFormGenerator or ReactFormBuilder.

    Example: If your variable key is JOHN, pass { JOHN: 'BASE64_STRING_HERE' } in the variables prop.

  2. Manage the rfb-cra example project with npm scripts

    master

    The rfb-cra package is a demonstration project bootstrapped with Create React App. You can manage the development lifecycle using the following npm scripts:

    • Development: Use npm start to run the app in development mode. The app will be available at http://localhost:3000 and will automatically reload on edits.
    • Testing: Use npm test to launch the test runner in interactive watch mode.
    • Production Build: Use npm run build to create an optimized, minified production build in the build folder.
    • Ejecting: Use npm run eject if you need full control over the underlying build configuration (Webpack, Babel, etc.). Warning: This is a one-way operation and cannot be undone.
    npm start
    npm test
    npm run build
    npm run eject
  3. Basic Usage of ReactFormBuilder

    master

    To use the form builder interface, import ReactFormBuilder from react-form-builder2 and include the required CSS. The builder is designed to interface with a JSON endpoint to load and save generated forms.

    import React from "react";
    import ReactDOM from "react-dom";
    import { ReactFormBuilder } from "react-form-builder2";
    import "react-form-builder2/dist/app.css";
    
    ReactDOM.render(<ReactFormBuilder />, document.body);
  4. Register and use Custom Components

    master

    You can extend the form builder with custom components using the Registry from react-form-builder2.

    1. Define the component

    For components that need to interact with form state, use React.forwardRef to pass the ref and props (like name, defaultValue, disabled).

    2. Register the component

    Use Registry.register(name, component) to add it to the library.

    3. Add to Toolbar

    Define a new item in your toolbarItems array with type: "custom". If the component uses a ref, set forwardRef: true.

    4. Use in Builder

    Pass the updated toolbarItems to ReactFormBuilder.

    import { ReactFormBuilder, ElementStore, Registry } from "react-form-builder2";
    
    // 1. Define
    const MyInput = React.forwardRef((props, ref) => {
      const { name, defaultValue, disabled } = props;
      return (
        <input
          ref={ref}
          name={name}
          defaultValue={defaultValue}
          disabled={disabled}
        />
      );
    });
    
    // 2. Register
    Registry.register("MyInput", MyInput);
    
    // 3. Define Toolbar Item
    const items = [
      {
        key: "MyInput",
        element: "CustomElement",
        component: MyInput,
        type: "custom",
        forwardRef: true,
        field_name: "my_input_",
        name: "My Input",
        icon: "fa fa-cog",
        props: { test: "test_input" },
        label: "Label Input",
      },
    ];
    
    // 4. Use
    <ReactFormBuilder toolbarItems={items} />
  5. Collect form data from ReactForm

    master

    When onSubmit, onChange, or onBlur is triggered, ReactForm provides a collection of data objects. Each object follows this structure:

    {
      "id": "field_id",
      "name": "field_name",
      "custom_name": "custom_name_or_field_name",
      "value": "field_value"
    }

    Data Collection Behavior

    • Checkboxes/RadioButtons: The value is an array of keys or values (depending on option_key_value) for all selected options.
    • Trimming: When onSubmit is called, string values are automatically trimmed.
    • Signature: For Signature elements, the value is the base64 encoded PNG string (excluding the data URI prefix) of the signature canvas.
  6. Configure validation for Email, Phone, and Correctness

    master

    The ReactForm component includes built-in validation for specific element types:

    1. EmailInput: Validates using a standard email regex. Errors are reported if the format is invalid.
    2. PhoneNumber: Validates using a regex supporting various formats (e.g., +1-123-456-7890, (123) 456-7890).
    3. Correctness: If the validateForCorrectness prop is set to true, the form compares the user's input against the correct property in the field configuration. This applies to Rating (exact match) and other elements (case-insensitive trimmed match).
    4. Required Fields: If required: true is set on a field, the form will fail validation if the value is empty or (for checkboxes/radio buttons) if no options are selected.
  7. Customize ReactFormGenerator UI

    master

    You can override the default submit and back buttons in ReactFormGenerator by providing custom components to the submitButton and backButton props.

    <ReactFormGenerator
      data={form}
      toolbarItems={items}
      onSubmit={handleSubmit}
      actionName="Set this to change the default submit button text"
      submitButton={
        <button type="submit" className="btn btn-primary">
          Submit
        </button>
      }
      backButton={
        <a href="/" className="btn btn-default btn-cancel btn-big">
          Back
        </a>
      }
    />
  8. Configure ReactFormBuilder Props

    master

    The ReactFormBuilder component accepts several props to manage data loading, saving, and the toolbar interface:

    • url: The GET endpoint to load the initial JSON form data.
    • saveUrl: The POST endpoint where the built form JSON will be saved.
    • toolbarItems: An array of objects defining the items available in the builder's toolbar (e.g., headers, paragraphs, or custom elements).
    • customToolbarItems: Use this instead of toolbarItems when providing a custom set of items.
    • edit: Boolean to enable editing mode.
    • data: The form JSON data.
    • renderEditForm: A function to provide a custom field edit form component.
    var items = [
      {
        key: "Header",
        name: "Header Text",
        icon: "fa fa-header",
        static: true,
        content: "Placeholder Text...",
      },
      {
        key: "Paragraph",
        name: "Paragraph",
        static: true,
        icon: "fa fa-paragraph",
        content: "Placeholder Text...",
      },
    ];
    
    <ReactFormBuilder
      url="path/to/GET/initial.json"
      toolbarItems={items}
      saveUrl="path/to/POST/built/form.json"
    />;
  9. Generate a form with ReactFormGenerator

    master

    Once a form is built and saved as JSON, use ReactFormGenerator to render the actual form for end-users to fill out. This component handles form submission and data rendering.

    import React from "react";
    import ReactDOM from "react-dom";
    import { ReactFormGenerator } from "react-form-builder2";
    import "react-form-builder2/dist/app.css";
    
    ReactDOM.render(
      <ReactFormGenerator
        form_action="/path/to/form/submit"
        form_method="POST"
        task_id={12}
        answer_data={JSON_ANSWERS}
        authenticity_token={AUTH_TOKEN}
        data={JSON_QUESTION_DATA}
      />,
      document.body
    );