rc-formly
/

Rc Formly Documentation

An open source JSON forms library for browsers using React.js and Formik library


rc-formly is a React.js libary which has components to help to help customize and render JavaScript/JSON configured forms.

Installation

Installing rc-formly only takes a single command and you're ready to roll.

npm install @rc-formly/core

Example

The following code demonstrates a basic usage example:

import React, { useState, FC } from 'react';
import { 
    IFormlyTypeDefinition, IWrapperOption, 
    RcFormlyForm,  RcFormlyProvider, IValidatorMessageOption 
} from '@rc-formly/core';

const BasicStory: FC = () => {
const types: IFormlyTypeDefinition[] = [
        {
            name: 'basicInput',
            component: InputFieldType
        }
    ];

    const wrappers: IWrapperOption[] = [
        {
            name: 'formElementWrapper',
            component: FormElementWrapper
        }
    ];

    const validatorMessages: IValidatorMessageOption[] = [
        {
            name: 'required',
            message: (value, field) => {
                return `Field '${field.templateOptions.label}' is required!`;
            }
        },
        {
            name: 'minLength',
            message: (value, field) => {
                return `Field '${field.templateOptions.label}' needs to have atleast ${field.templateOptions.minLength} characters!`;
            }
        }
    ];

    const initialValues = {
        firstName: ''
    };
    const [submittedModel, setSubmittedModel] = useState(null);

    const fields: IFormlyFieldConfig[] = [
        {
            key: 'firstName',
            type: 'basicInput',
            templateOptions: {
                label: 'First name',
                minLength: 5,
                required: true
            }
        }
    ];

    const onSubmit = (model: any) => {
        console.log(`Submitted ${JSON.stringify(model)}`);

        setSubmittedModel(model);
    };

    return (
        <RcFormlyProvider 
            types={types} 
            wrappers={wrappers} 
            validatorMessages={validatorMessages}>
            <RcFormlyForm model={initialValues} fields={fields} onSubmit={onSubmit} render={(formikProps, renderFields) => (
                <form onSubmit={formikProps.handleSubmit}>
                    { renderFields() }
                    <button type="submit" style={ { marginTop: '10px' }}>
                        Submit
                    </button>
                </form>
            )} />
            <div>
                Submitted value: { JSON.stringify(submittedModel)}
            </div>
        </RcFormlyProvider>
    );
}

API reference