DRY (Don’t repeat yourself) is a principle of software development aimed at reducing repetition of software patterns, replacing it with **abstractions **or using data normalization to avoid redundancy. And while the nature of React development in rich forms application will include a lot of repetition in dealing with the state variables, validations, and rendering fields; I present in this article a way to abstract these operations through an abstract React component.


The first step is to create a React component that will work as the abstract forms component which should be inherited from any view component that needs to access these features. An example of that component would be as next:

Image for post

Abstracting dealing with fields generation

Normally we need to have the same way of rendering fields, that contains usually the following steps:

1- Choosing the input component (Of course, in that case, don’t forget to implement your own low-level input components :))

2- Choosing the structure of the group and the needed CSS classes

3- Rendering the error message component

4- Rendering the validation classes logic

Next is an example of how to handle that inside the code:

Image for post

This function will render a form group (Bootstrap form group) that includes a label, a placeholder for the low-level component, a help block to render the errors inside. I am using also a ready component for displaying errors.

Please noticed that I made another function to render the low-level input component according to the type of the field, the function code will be as next:

Image for post

Usually, I prefer starting the name of the function with _ if its a private function.

We can notice that for three types (password, text, and email) we are rendering a Textbox component. And so on for each other type, we will render the low-level component that suits the type. Like file uploaded for image type and date picker for date type…etc.

And we see that in case of error, has-error will be appended to component CSS classes where we can style that as we want to show the error (Like a red border around the input component).

#javascript #abstraction #web-development #programming #coding #react

Abstract Forms Component in React
2.95 GEEK