1.0.1 • Published 6 months ago

react-dynamic-kit v1.0.1

Weekly downloads
-
License
MIT
Repository
-
Last release
6 months ago

react-dynamic-kit

react-dynamic-kit is a lightweight and flexible library for creating dynamic, reusable, and highly customizable React components.

Installation

To install react-dynamic-kit, use npm Repository

  npm install react-dynamic-kit

Usage

react-dynamic-kit is a lightweight and flexible library for building dynamic and reusable components in React. It simplifies the creation of complex forms, interactive UI elements, and customizable components, making it ideal for rapidly developing scalable applications.

1. Dynamic Form

Features

  • 📦 Dynamic Form Components: Build forms with nested and conditional fields effortlessly.
  • ⚡ Highly Configurable: Tailor every component to your specific needs.

Properties

The DynamicForm component accepts the following properties:

1. DynamicFormProps

  • The DynamicForm component accepts the following properties:
PropertyTypeDescription
fieldsFieldSchema[]An array of field schemas defining the form fields.
formDefaultValueFormSchemaThe default values for the form fields.
onSubmit(data: FormSchema) => voidCallback function for form submission.
fetchAutocompleteOptions(data: string, fieldId: string) => Promise<SelectOption[]>Function to fetch autocomplete options for fields.
formViewModebooleanBoolean to determine if the form is in view mode (non-editable) or in edit mode.

2. FieldSchema

  • Each field in the form is described by a FieldSchema object, which can have the following properties:
NameTypeRequiredDetails
namestringtrueUnique identifier for the field
labelstringtrueLabel to display next to the input field
typeTextFieldTypetrueSpecifies the type of the field (e.g., text, email, password, etc.)
fieldTypeComponentTypetrueThe type of input component to be used (e.g., TextField, SelectField, RadioField, etc.)
dataTypeDataTypetrueSpecifies the expected data type for the field value (e.g., string, number, boolean, date)
groupNamestringfalseUsed to group related fields together
variantTextFieldVariantsfalseVariant of the MUI TextField component (e.g., outlined, filled, standard)
sequencenumberfalseControls the order in which fields appear in the form
validationValidationRulesfalseCustom validation rules for the field (e.g., required, min/max length, custom validation function)
dateValidationDateValidationRulesfalseDate-specific validation rules (e.g., disabled dates, max/min date, age validation)
optionsSelectOption[]falseList of options for select or multi-select fields (only applicable for select-type fields)
nestedRootValuestringfalseUsed when dealing with nested fields, refers to the root value for the nested data structure
placeholderstringfalsePlaceholder text for the input field
helperTextstringfalseHelper text for extra information about the field
tooltipstringfalseTooltip text displayed when the user hovers over the field
disabledbooleanfalseWhether the field is disabled and cannot be interacted with
isMultipleValuesbooleanfalseIf true, indicates the field can accept multiple values (e.g., multi-select fields)
nestedFieldsLimitnumberfalseSpecifies the maximum number of nested fields allowed in the form (applicable when isMultipleValues is true)
nestedFieldsFieldSchema[]falseArray of nested field schemas (applicable for complex forms with nested structures)

1. Field Types

  • The ComponentType defines the types of input components available for use in the DynamicForm. Each type corresponds to a specific input behavior.
fieldTypeDescription
textFieldA standard text input field
selectFieldA dropdown menu for single selection
multiSelectFieldA dropdown menu for multiple selections
radioFieldRadio buttons for exclusive selection
dateFieldA date picker input
autoCompleteFieldAn autocomplete input field

3. Field Validation Rules

  • Validation rules for fields
NameTypeRequiredDetails
requiredbooleanfalseWhether the field is required
numberNumberValidationRulesfalseRules specific to number fields (e.g., min/max values)
stringStringValidationRulesfalseRules specific to string fields (e.g., min/max length, regex pattern)
customValidation(value: string | number | boolean) => boolean | stringCustom validation function that can be used for more complex validation needs (e.g., value should not exceed a certain length)
maxSelectionsnumberfalseFor fields that allow multiple selections (e.g., multi-select), specifies the maximum number of selections allowed
errorMessagestringfalseCustom error message to be shown when validation fails

4. Date Validation Rules

NameTypeRequiredDetails
disabledDatesstring[]falseList of dates that should be disabled (e.g., "2024-11-05")
disabledMonthsnumber[]falseList of months to disable (0 = January, 11 = December)
disabledYearsnumber[]falseList of years to disable (e.g., 2024, 2025)
maxDatestringfalseSpecifies the maximum selectable date
minDatestringfalseSpecifies the minimum selectable date
defaultValuestringfalseDefault value for the date field (e.g., "2024-11-25")
disabledbooleanfalseWhether the date field should be disabled
disableFuturebooleanfalseWhether future dates should be disabled
disablePastbooleanfalseWhether past dates should be disabled
formatstringfalseThe date format to display (e.g., "YYYY-MM-DD")
readOnlybooleanfalseWhether the field is read-only
localestringfalseLocale for date formatting (e.g., "en-US")
timeZonestringfalseTime zone (e.g., "UTC")
ageValidation{ minAge?: number, maxAge?: number }falseAge validation rules for selecting dates (e.g., min/max age based on the selected date)

Example

import React from 'react';
import {DynamicForm} from "react-dynamic-kit" 

export interface userFromSchema {
  firstName: string;
  middleName: string;
  lastName: string; 
  email: string;
  dob: string;
  gender: string;
  phoneNumber: string;
  address: [{
    addressLineOne: string;
    addressLineTwo: string;
    village: string;
    town: string;
    district: string;
    state: string;
    country: string;
    addressType: string;
  }];
}

const user = () => {
  const defaultValue: userFromSchema = {
    firstName: 'sharwan',
    middleName: '',
    lastName: '',
    email: '',
    dob: '',
    gender: '',
    phoneNumber: '',
    address: [{
      addressLineOne: '',
      addressLineTwo: '',
      village: '',
      town: '',
      district: '',
      state: '',
      country: '',
      addressType: ''
    }]
  };

  const handleFormSubmit = async (data: userFromSchema) => {
    console.log(data);
  };

  const AutocompleteOptionsSearch = async (searchTerm: string, fieldId: string) => {
    try {
      console.log(searchTerm+fieldId);
      const response  = [
        { label: 'The Shawshank Redemption', value: "1994" },
        { label: 'The Godfather', value: "1972" },
        { label: 'The Godfather: Part II', value: "1974" },
        { label: 'The Dark Knight', value: "2008" },
        { label: '12 Angry Men', value: "1957" },
        { label: "Schindler's List", value: "1993" },
        { label: 'Pulp Fiction', value: "1994" }
      ];
	  
      const result = await response;
      return result || []; 
    } catch (error) {
      console.error('Error fetching data:', error);
      return [];
    }
  };
  

  return (
    <div>
        <DynamicForm
          fields={userForm}
          formDefaultValue={defaultValue}
          onSubmit={handleFormSubmit}
          formViewMode={false}
          getAutocompleteOptions={AutocompleteOptionsSearch}
        />
    </div>
  );
};

export default user;

👉 Authors

  • Sharwan Kumar (SK)