@bright-lab/react-dynamic-form v0.0.34
ā
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
Rule | Description | Parameters | Example Usage |
---|---|---|---|
required | Ensures the field is not empty. | None | { rule: 'required' } |
min | Validates that the value is greater than or equal to a minimum value. | value (number) | { rule: 'min', params: { value: 5 } } |
max | Validates that the value is less than or equal to a maximum value. | value (number) | { rule: 'max', params: { value: 10 } } |
number_range | Validates that the value falls within a specified range. | min (number), max (number) | { rule: 'number_range', params: { min: 5, max: 10 } } |
min_length | Validates the minimum length of the input. | length (number) | { rule: 'min_length', params: { length: 3 } } |
max_length | Validates the maximum length of the input. | length (number) | { rule: 'max_length', params: { length: 10 } } |
pattern | Validates the input against a regular expression. | regex (string) | { rule: 'pattern', params: { regex: '^[a-z]+$' } } |
numeric | Checks if the input is a valid number. | None | { rule: 'numeric' } |
boolean | Validates if the input is a boolean value (true or false ). | None | { rule: 'boolean' } |
inclusion | Ensures the input is one of the specified values. | values (array of strings) | { rule: 'inclusion', params: { values: ['option1', 'option2'] } } |
exclusion | Ensures 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.
9 months ago
11 months ago
11 months ago
10 months ago
10 months ago
10 months ago
10 months ago
10 months ago
10 months ago
10 months ago
10 months ago
9 months ago
10 months ago
10 months ago
10 months ago
11 months ago
12 months ago
12 months ago
12 months ago
12 months ago
12 months ago
12 months ago