React JSON Form: Configurable Component Library
Developing dynamic forms in React can be streamlined with a well-structured component library. This article explores the Biblioteca de Componentes, a React form component library designed to be configured and rendered dynamically using JSON objects. This approach simplifies form creation, enhances flexibility, and promotes code reusability.
Overview
The Biblioteca de Componentes offers a suite of React form components configured and rendered dynamically from a JSON object. This eliminates the need to hardcode form structures, making it easier to manage complex forms and adapt to changing requirements. The library is designed to be extensible, allowing developers to add custom components and validation rules as needed.
🚀 How to Use the Library
The system renders fields by reading the type key from the JSON, which maps to the corresponding component registered in your componentRegistry. This registry acts as a central hub, connecting the JSON configuration to the actual React components that will be rendered. This approach ensures that the form structure is defined in a data-driven manner, making it highly adaptable and maintainable.
Consider this carefully because understanding this is key to maximizing your productivity and efficiency when working with the library. By leveraging the componentRegistry, you can easily extend the library with custom components and tailor the form rendering process to meet your specific needs.
Example of Basic Configuration (formConfig.json)
{
"title": "Sample Form",
"description": "Configurable form via JSON.",
"components": [
{ "type": "nome", "id": "nome", "label": "Full Name" },
{ "type": "address", "id": "endereco", "label": "Location" }
]
}
In this example, the formConfig.json file defines a simple form with two components: a text input for the full name (nome) and an address field (address). The type key specifies the component to be used, while the id and label keys provide additional configuration options. When the form is rendered, the library will use the componentRegistry to map the nome and address types to the corresponding React components, which will then be displayed on the screen.
🧩 Component Catalog
The library provides a rich set of pre-built components that cover a wide range of form field types. These components are designed to be highly customizable, allowing you to tailor their appearance and behavior to match your specific design requirements. Let's explore the available components in detail.
Data Input and Formatting Fields
These components return basic formatted values (strings or numbers).
- Nome (type: "nome"): Text field with length validation and only letters.
- Email (type: "email"): Formatted and validated input for email address.
- CPF (type: "cpf"): Formatted and validated field with selected digit.
- CEP (type: "cep"): Field formatted for Postal Code.
- Phone (type: "phone"): Field formatted for telephone contact (DDD).
- URL (type: "url"): Field for project links.
- Senha (type: "senha"): Hidden password field.
- Textarea (type: "textarea"): Text area for long messages.
- Idade (type: "idade"): Numeric input for age, with value limits.
- Moeda (type: "currency"): Formatted input for monetary values (R$).
These input components are essential for capturing user data in a consistent and reliable manner. Each component includes built-in validation rules to ensure that the data entered by the user is in the correct format. For example, the email component validates that the input is a valid email address, while the idade component ensures that the input is a number within the specified range.
By using these pre-built input components, you can save time and effort in form development and ensure that your forms are robust and user-friendly.
Selection, Boolean, and Interaction
- Select (type: "select"): Simple dropdown list (single selection).
- Select Multiple (type: "selectMultiple"): Selection of multiple items from a list.
- Rating (type: "rating"): Visual rating by stars.
- Gênero (type: "genero"): Gender/identity selection (Dropdown).
- Termos (type: "termos"): Checkbox for terms acceptance.
- Escolha (Radio) (type: "radioBinary"): Explicit binary choice (Yes/No).
- CheckboxGroup (type: "checkboxGroup"): List of checkboxes (multiple choices).
- Habilidades (type: "tags"): Dynamic list of keywords/tags.
- Data de Nascimento (type: "data"): Data selection field.
These selection and interaction components enhance the user experience by providing intuitive ways to input data and make choices. The select and selectMultiple components allow users to select options from a predefined list, while the rating component provides a visual way to rate something. The termos component is a checkbox that users must check to accept the terms and conditions, and the radioBinary component presents an explicit binary choice.
Structural and Object Components
These components manage complex data structures or layout organization.
- Endereço (type: "address"): Groups and manages all fields of an address, returning a single object.
- Dynamic List (type: "repetidora"): Allows the user to add and remove repeated groups of fields (ex: Professional History).
- ImgUpload (type: "imgUpload"): Captures text (description) and an image file.
- Cabeçalho/Título (type: "cabeçalho"): Define a section title to organize the form.
- Divisor (type: "divider"): Insert a horizontal line for visual separation.
- Texto Informativo (type: "textInfo"): Static text block for warnings or instructions.
These structural and object components are designed to manage complex data structures and organize the form layout. The address component groups and manages all the fields of an address, returning a single object. The dynamic list component allows users to add and remove repeated groups of fields. The imgUpload component captures text and an image file. The header component defines a section title to organize the form. The divider component inserts a horizontal line for visual separation, and the textInfo component provides a static text block for warnings or instructions.
⚙️ Configurations and Validation
All behavior and appearance properties are passed directly from the JSON (e.g., label, placeholder, required: true) to the React component.
The ability to configure these properties directly from the JSON object provides a high degree of flexibility and control over the form's appearance and behavior. This approach makes it easy to customize the form to meet specific design requirements without modifying the underlying React component code. For example, you can easily change the label of a field, add a placeholder text, or make a field required by simply modifying the corresponding properties in the JSON object.
Note on Validation
Validation logic (required, minLength) is currently written within the JSX code of each component.
Currently, the library embeds validation logic within the JSX code of each component. While this approach works, it can become cumbersome to manage and maintain as the number of components and validation rules grows. Therefore, the library developers are exploring a more flexible and extensible approach to validation.
Recommended Next Step
Migrate to a configurable validation structure by array (validations: []) that we discussed, using the runValidations function to make the rules dynamic via JSON.
To address the limitations of the current validation approach, the library developers recommend migrating to a configurable validation structure based on arrays. This approach would involve defining validation rules as an array of objects, with each object specifying the type of validation to perform and any associated parameters. By using a runValidations function, the library could dynamically apply these validation rules to each component based on the JSON configuration.
This approach would make it easier to add, remove, and modify validation rules without modifying the underlying component code. It would also allow developers to define more complex validation rules by combining multiple validation types.
In conclusion, the Biblioteca de Componentes offers a powerful and flexible approach to building dynamic forms in React. By leveraging JSON configuration and a component registry, developers can create forms that are easy to manage, customize, and extend. The library's rich set of pre-built components and extensible validation architecture make it a valuable tool for any React developer working with forms. Consider exploring more about React and JSON on Reactjs.