0.0.34 • Published 9 months ago

@bright-lab/react-dynamic-form v0.0.34

Weekly downloads
-
License
MIT
Repository
github
Last release
9 months ago

npm downloads minizipped size npm latest package

​

Overview

The React Dynamic Form package is a powerful tool for building dynamic forms in React applications. It provides a flexible and customizable approach to creating forms with various input types and validation rules. This package is ideal for developers who need to generate forms dynamically based on configuration and manage form state and validation effortlessly.

Getting Started

Install the package using npm:

npm install @bright-lab/react-dynamic-form

React Dynamic Form Package

This package enables you to create and manage dynamic forms with ease, offering support for different input types and custom validation rules.

Setup

First, import the necessary components and types into your application:

Define Global Fields

Setup your Global fields

import {
  DynamicForm,
  FormProvider,
  IGlobalFieldConfig,
  IFieldConfig,
  IBaseFieldProps
} from '@bright-lab/react-dynamic-form';
import '@bright-lab/react-dynamic-form/css'; // if you are using the grid system

const globalFieldsConfig: IGlobalFieldConfig[] = [
  {
    type: 'text',
    render: ({ label, name, value, onChange, validateField, error } : IBaseFieldProps) => (
      <div>
        <label>{label}</label>
        <input
          placeholder="first name"
          name={name}
          value={value}
          onChange={onChange}
          onBlur={validateField}
        />
        {error && <p>{error}</p>}
      </div>
    ),
  },
  {
    type: 'select',
    render: ({ label, name, value, onChange, validateField, payload, error } : IBaseFieldProps) => {
      const [options, setOptions] = React.useState<{ id: number; title: string }[]>([]);

      React.useEffect(() => {
        const fetchOptions = async () => {
          try {
            const response = await fetch(payload?.url);
            const data = await response.json();
            setOptions([{ id: 0, title: 'Select an option' }, ...data]);
          } catch (error) {
            console.error('Error fetching options:', error);
          }
        };

        fetchOptions();
      }, [payload?.url]);

      return (
        <div>
          <p>{label}</p>
          <select
            name={name}
            value={value}
            onChange={onChange}
            onBlur={validateField}
          >
            {options.map((option) => (
              <option key={option.id} value={option.id}>
                {option.title}
              </option>
            ))}
          </select>
          {error && <p>{error}</p>}
        </div>
      );
    },
  },
  // Add more field configurations as needed
];

Define Form Fields and Validation

Set up your form fields and validation rules:

const fields: IFieldConfig[] = [
  {
    label: 'First Name',
    type: 'text',
    name: 'first_name',
    grid: {
      xs: 12,
      md: 6,
    },
    validation: [
      {
        rule: 'required',
        message: 'Please enter your first name',
      },
      {
        rule: 'min_length',
        params: { length: 3 },
        message: 'First name must be at least 3 characters',
      },
    ],
  },
  {
    label: 'Email',
    type: 'email',
    name: 'email',
    grid: {
      xs: 12,
      md: 6,
    },
    validation: [
      { rule: 'required', message: 'Email is required' },
      {
        rule: 'pattern',
        params: { regex: '^[\\w-\\.]+@([\\w-]+\\.)+[\\w-]{2,4}$' },
        message: 'Invalid email format',
      },
    ],
  },
  {
    label: 'Options',
    type: 'select',
    name: 'options',
    payload: {
      url: 'https://jsonplaceholder.typicode.com/todos',
    },
    validation: [
      {
        rule: 'required',
        message: 'This field is required',
      },
    ],
  },
  // Add more field configurations as needed
];

Use the Form in Your Component

Wrap your App with the FormProvider and use the DynamicForm component:

function Example() {
  const initialValues = {
    first_name: 'Chris',
    email: 'chris@hotmail.com',
    // etc..
  };

  return (
    <FormProvider globalFieldsConfig={globalFieldsConfig}>
      <div className="container">
        <DynamicForm
          fields={fields}
          initialValues={initialValues}
          onValuesUpdate={(formValues) => console.log('formValues', formValues)}
          isError={(value) => console.log('isError', value)}
          style={{ rowGap: '16px', columnGap: '16px' }}
        />
      </div>
    </FormProvider>
  );
}

export default Example;

API

FormProvider

Provides the context for the DynamicForm component.

Props

  • globalFieldsConfig: Configuration for global field types.

DynamicForm

Renders a form based on the provided field configurations and handles state management.

Props

  • fields: Configuration for the form fields.
  • initialValues: Initial values for the form fields.
  • onValuesUpdate: Callback for form value updates.
  • isError: Callback for error state.
  • style: Custom styles.
  • className: Custom class name.

Types

  • IGlobalFieldConfig: Type for global fields.
  • IFieldConfig: Type for form fields.
  • IBaseFieldProps: Type for renderer field.

Validation Rules

This package supports various validation rules to ensure the data entered into the form fields meets the required criteria. Below is a table describing each rule, description and its parameters

RuleDescriptionParametersExample Usage
requiredEnsures the field is not empty.None{ rule: 'required' }
minValidates that the value is greater than or equal to a minimum value.value (number){ rule: 'min', params: { value: 5 } }
maxValidates that the value is less than or equal to a maximum value.value (number){ rule: 'max', params: { value: 10 } }
number_rangeValidates that the value falls within a specified range.min (number), max (number){ rule: 'number_range', params: { min: 5, max: 10 } }
min_lengthValidates the minimum length of the input.length (number){ rule: 'min_length', params: { length: 3 } }
max_lengthValidates the maximum length of the input.length (number){ rule: 'max_length', params: { length: 10 } }
patternValidates the input against a regular expression.regex (string){ rule: 'pattern', params: { regex: '^[a-z]+$' } }
numericChecks if the input is a valid number.None{ rule: 'numeric' }
booleanValidates if the input is a boolean value (true or false).None{ rule: 'boolean' }
inclusionEnsures the input is one of the specified values.values (array of strings){ rule: 'inclusion', params: { values: ['option1', 'option2'] } }
exclusionEnsures the input is not one of the specified values.values (array of strings){ rule: 'exclusion', params: { values: ['option1', 'option2'] } }

Changelog

The changelog is regularly updated to reflect the changes and updates in each new release.

0.0.34-alpha-6

9 months ago

0.0.31

11 months ago

0.0.32

11 months ago

0.0.34

10 months ago

0.0.33-alpha-4

10 months ago

0.0.33-alpha-5

10 months ago

0.0.34-alpha-1

10 months ago

0.0.34-alpha-2

10 months ago

0.0.34-alpha-3

10 months ago

0.0.34-alpha-4

10 months ago

0.0.33-alpha-1

10 months ago

0.0.34-alpha-5

9 months ago

0.0.33-alpha-2

10 months ago

0.0.33-alpha-3

10 months ago

0.0.32-alpha-1

10 months ago

0.0.3

11 months ago

0.0.2

12 months ago

0.0.2-alpha.4

12 months ago

0.0.2-alpha.2

12 months ago

0.0.2-alpha.1

12 months ago

0.0.2-alpha.0

12 months ago

0.0.1

12 months ago