antd-schema-form

repository·master·Indexed 41 days ago

https://github.com/duan602728596/antd-schema-form

A library built on Ant Design that generates interactive forms using JSON Schema configurations. It features a SchemaForm component with support for custom rendering via customComponent and customTableRender, utility functions for data transformation (getKeysFromObject, getObjectFromValue, getValueFromObject), and specialized configuration keys for string, boolean, and array types. Version 5.1.0.

Tokens
11K
Snippets
29
Records
41
Agent score
48%

What's inside antd-schema-form

  1. Manage field IDs and paths in JSON Schema

    master

    Every attribute in the schema requires an id. The convention is to use a path starting with $root and separating segments with /.

    • For objects, child properties must include /properties/ in their ID path.
    • For arrays, items must include /items in their ID path.

    This ensures the schema ID corresponds correctly to the JSON key names used in the form data.

    {
      "id": "$root",
      "type": "object",
      "properties": {
        "key": {
          "id": "$root/properties/key",
          "type": "string"
        }
      }
    }
    
    {
      "id": "$root",
      "type": "array",
      "items": {
        "id": "$root/items",
        "type": "string"
      }
    }
  2. Use custom properties for UI control

    master

    Use properties prefixed with $ to control how the form renders and behaves. Common custom properties include:

    • $componentType: Forces the field to render as a specific component (e.g., select, radio, date, textArea) when no oneOf is present.
    • $order: Defines the display order (smaller numbers appear first; default is 0).
    • $hidden: Hides the field from the UI while keeping its value in the form state.
    • $disabled: Disables the component.
    • $required: Enables validation requiring the value to exist.
    • $defaultValue: Sets the initial value.
    • $placeholder: Sets the input placeholder.
    • $formItemProps: Passes props directly to the underlying Ant Design Form.Item component.
    • $oneOfComponentType: Specifies the component to render when using the oneOf keyword.
  3. Configure JSON Schema for antd-schema-form

    master

    The form is driven by a JSON Schema configuration following the JSON Schema Draft 07 standard.

    To extend the standard schema for UI-specific needs, antd-schema-form uses custom properties prefixed with a $ sign.

    Core Schema Properties

    • type: Defines the data type (string, number, integer, boolean, array, object). This determines the default component rendered.
    • title: The label/title for the form field.
    • description: A description for the field.
    • id: A unique identifier for the property. It is recommended to use a path-like convention starting with $root and using / as a separator (e.g., $root/key1/key2).
      • For type: "object", include /properties in the path (e.g., $root/properties/key).
      • For type: "array", include /items in the path (e.g., $root/items).
    • oneOf: An array of schema objects used to implement conditional logic (multiple possible types).
    {
      "id": "$root",
      "type": "object",
      "properties": {
        "key": {
          "id": "$root/properties/key",
          "type": "string"
        }
      }
    }
  4. Configure antd-schema-form using JSON Schema

    master

    The form is configured using JSON Schema (Draft 07). The library maps JSON schema types to Ant Design components.

    Core Schema Attributes:

    • type: Data type (string, number, integer, boolean, array, object).
    • title: The title of the form or field.
    • description: A description of the field.
    • properties: (For type="object") Defines the child attributes.
    • items: (For type="array") Defines the schema for array elements.
    • required: (For type="object") An array of strings listing required property names.
    • oneOf: An array of schema objects for conditional logic.

    Custom Extension Attributes: To support form-specific features, the library uses custom properties prefixed with $. Examples include $componentType, $order, $hidden, $disabled, and $formItemProps.

    {
      "id": "$root",
      "type": "object",
      "properties": {
        "key": {
          "id": "$root/properties/key",
          "type": "string"
        }
      }
    }
  5. Create custom rendering components for SchemaForm

    master

    You can render custom UI components by providing a customComponent object to the SchemaForm component. The structure of the functions within this object depends on whether the schema type is an object or another type.

    For non-object types

    When the schema type is not object, define functions that accept:

    • item (object): The JSON schema for the current component (contains id, title, etc.).
    • form (object): The Ant Design form instance.
    • required (boolean): Whether the field is required.

    For object types

    When the schema type is object (or contains a oneOf attribute), define functions that accept:

    • item (object): The JSON schema for the current component.
    • form (object): The Ant Design form instance.
    • element (React.ReactNode | React.ReactNodeArray): The already rendered React component for this schema node.

    To trigger a custom component, use the $componentType key in your JSON schema to match a key in your customComponent object.

    import React from 'react';
    import SchemaForm from 'antd-schema-form';
    import 'antd-schema-form/style/antd-schema-form.css';
    
    const customComponent = {
      // Used for non-object types
      custom({ item, form, required }) {
        return <Input placeholder="Custom rendering component." required={ required } />;
      },
      
      // Used for object types
      objectCustom({ item, form, element }) {
        return <div>{ element }</div>;
      },
    };
    
    const schemaJson = {
      id: '$root',
      type: 'string',
      title: 'Custom rendering component',
      $componentType: 'custom' // Matches the 'custom' key in customComponent
    };
    
    // Usage
    <SchemaForm json={ schemaJson } customComponent={ customComponent } />
  6. Custom table column rendering component

    master

    To customize how data is rendered within a table (when using an array type in your schema), use the customTableRender prop on SchemaForm.

    Implementation

    1. Define a customTableRender object where each key is a function.
    2. Each function receives the following parameters:
      • text (any): The currently rendered value.
      • record (object): The current row's data information.
      • index (number): The column index.
      • root (object): JSON schema information (e.g., id, title).
      • form (object): The Ant Design form instance.
    3. In your JSON schema, for the specific property you want to customize, set $tableRender to the key name used in your customTableRender object.

    Example

    If your schema property has $tableRender: 'custom', the custom function in your customTableRender object will be invoked.

    import React from 'react';
    import SchemaForm from 'antd-schema-form';
    import 'antd-schema-form/style/antd-schema-form.css';
    
    const customTableRender = {
      // The key 'custom' matches the $tableRender value in the schema
      custom({ text, record, index, root, form }) {
        return <span>{ text }</span>;
      },
    };
    
    const schemaJson = {
      id: '$root',
      type: 'array',
      title: 'Table column rendering component',
      items: {
        id: '$root/items',
        type: 'object',
        title: 'Table data',
        properties: {
          data: {
            id: '$root/items/properties/data',
            type: 'string',
            title: 'Data',
            $tableRender: 'custom' // Triggers the 'custom' function in customTableRender
          } 
        }
      }
    };
    
    // Usage
    <SchemaForm json={ schemaJson } customTableRender={ customTableRender } />
  7. Customize table column rendering with `customTableRender`

    master

    To customize how individual columns are rendered within a table (when using an array type schema), use the customTableRender prop on SchemaForm.

    In your JSON schema, set the $tableRender property to a key that matches a function defined in your customTableRender object.

    Each function in the customTableRender object receives the following arguments:

    • text (any): The current value being rendered.
    • record (object): The data for the current row.
    • index (number): The index of the current row.
    • root (object): The JSON schema information (id, title, etc.).
    • form (object): The Ant Design form instance.

    Signature: (text, record, index, root, form) => React.Node

    import SchemaForm from 'antd-schema-form';
    
    const customTableRender = {
      // The key 'custom' matches the $tableRender value in schema
      custom(text, record, index, root, form) {
        return <span style={{ color: 'blue' }}>{ text }</span>;
      },
    };
    
    const schemaJson = {
      id: '$root',
      type: 'array',
      title: 'Table Column Customization',
      items: {
        id: '$root/items',
        type: 'object',
        properties: {
          data: {
            id: '$root/items/properties/data',
            type: 'string',
            $tableRender: 'custom' // Matches the key in customTableRender
          }
        }
      }
    };
    
    // Usage
    <SchemaForm json={ schemaJson } customTableRender={ customTableRender } />
  8. Load components as needed in SchemaForm

    master

    To reduce the initial bundle size and avoid loading all available components, you can manually import only the specific components you need and pass them to the customComponent prop of SchemaForm.

    By providing a customComponent object, you override the default component mapping. You can selectively include standard types like defaultString, defaultNumber, etc., from the antd-schema-form/es/components/custom/custom path.

    import React from 'react';
    import { render } from 'react-dom';
    import SchemaForm from 'antd-schema-form/es/SchemaForm';
    
    // Only import the specific components you need
    import {
      defaultString,
      defaultNumber,
      defaultBoolean,
      defaultArray,
      defaultObject,
      defaultOneOf
    } from 'antd-schema-form/es/components/custom/custom';
    
    render(
      <SchemaForm
        customComponent={{
          // Pass the selectively imported components here
          defaultString,
          defaultNumber,
          defaultBoolean,
          defaultArray,
          defaultObject,
          defaultOneOf
          // ...other custom components
        }}
      />
    );
  9. Development and testing commands

    master

    To work with the project locally:

    • Development: Run npm run dev to start the development server. Access the demo at http://127.0.0.1:5050.
    • Build and Test: Run npm run build and npm run test to build the project and execute test cases. View results at http://127.0.0.1:6060.
    npm run dev
    npm run build
    npm run test
  10. Migrate customComponent and customTableRender in v5.0.0

    master

    When upgrading to v5.0.0, note that the function parameters for customComponent and customTableRender have changed from multiple arguments to a single object type. Ensure your custom rendering logic is updated to destructure properties from this object instead of receiving them as positional arguments.

    // Before v5.0.0
    // customComponent: (props, field, form) => ...
    
    // v5.0.0 and later
    // customComponent: ({ props, field, form }) => ...
  11. Create custom rendering components with `customComponent`

    master

    You can render personalized components by providing a customComponent object to the SchemaForm component. The keys in this object correspond to the $componentType value defined in your JSON schema.

    Depending on the type of the schema field, the function signature for your custom component changes:

    For non-object types

    When the schema type is not object, your function receives:

    • item (object): The JSON schema information for the current component (id, title, etc.).
    • form (object): The Ant Design form instance.
    • required (boolean): Indicates if the field is mandatory.

    Signature: ({ item, form, required }) => React.Node

    For object types

    When the schema type is object (or contains oneOf), your function receives:

    • item (object): The JSON schema information.
    • form (object): The Ant Design form instance.
    • element (React.ReactNode): The React component to be rendered.

    Signature: ({ item, form, element }) => React.Node

    import SchemaForm from 'antd-schema-form';
    import 'antd-schema-form/style/antd-schema-form.css';
    
    const customComponent = {
      // For non-object types
      custom({ item, form, required }) {
        return <Input placeholder="Custom Component" required={ required } />;
      },
    
      // For object types
      objectCustom({ item, form, element }) {
        return <div className="custom-wrapper">{ element }</div>;
      },
    };
    
    const schemaJson = {
      id: '$root',
      type: 'string',
      title: 'Custom Component Example',
      $componentType: 'custom' // Matches the key in customComponent
    };
    
    // Usage
    <SchemaForm json={ schemaJson } customComponent={ customComponent } />
  12. Install and use antd-schema-form

    master

    antd-schema-form is a library based on Ant Design that allows you to quickly generate interactive forms using JSON Schema.

    Prerequisites:

    • React version >=16.7.0
    • Ant Design version >=5 (recommended)

    Basic Usage:

    1. Import the SchemaForm component and its associated CSS.
    2. Define a JSON Schema object.
    3. Render the <SchemaForm /> component with the json prop.

    Useful utility functions exported by the package:

    • getKeysFromObject: Retrieves all keys from the schema.json.
    • getObjectFromValue: Formats an object into the value format required by the form.
    • getValueFromObject: Formats values obtained from the form back into an object.
    import React from 'react';
    import ReactDOM from 'react-dom';
    import SchemaForm, {
      getKeysFromObject,  // Get all keys from schema.json
      getObjectFromValue, // Format object to form values
      getValueFromObject  // Format form values to object
    } from 'antd-schema-form';
    import 'antd-schema-form/style/antd-schema-form.css'; // Import styles
    
    // json schema
    const json = {
      id: '$root',
      type: 'object',
      title: '$root',
      properties: {}
    };
    
    ReactDOM.render(
      <SchemaForm json={ json } />,
      document.getElementById('app')
    );