Build a Perfect React Form with Hook - CodAffection

Build a Perfect React Form with Hook

How to build react form with react hook

In this article, we’ll discuss how to design/ build a perfect react form by applying best practices from software development. So that you can keep your application more organized and clean.

In this tutorial you’ll build a form in react application with an example app that store details of employees in a company. we’ve included commonly used controls to give you an idea on how to apply discussed concepts in real a application. In a practical application most of you must be using an UI react framework. So in this tutorial I will be using popular React UI framework – Material UI. Don’t worry you could follow same steps for other UI frameworks also or even if you are work with plain HTML.

GitHub Repository : http://bit.ly/3p1khFa

Keep it DRY

DRY stands for “Don’t Repeat Yourself”. It is a software development principle aimed at reducing repetition of software patterns.

“Every piece of knowledge must have a single, unambiguous, authoritative representation within a system”

The Pragmatic Programmer – Book

This concept is more important in case forms in an application because, in forms across the application, we repeatedly use common controls like input, button, select, checkbox, etc. Whether you use React UI Frameworks or not, form controls across the entire application will be designed with a unique style. If we were able to create a single re-usable component for each form control we could avoid writing the same code again and again.

Architect Form and its Control

Hope you’ve created a brand new react app with create-react-app . The structure of the application would be as follows.

* src
|
|--+components
|
|--+controls
|
|--+pages

there are 3 folders, inside controls folder, we create components for form controls and rest of the reusable components will be there in components folder. pages contains components for each page/ route in this application.

application structure for building react form

The above architecture of the app will provide necessary abstraction in page components. Meaning without knowing how these controls are designed or how it works, you could use them like a normal HTML form controls.

Let’s look them in action. Rest of the advantages of above structure can be discussed later.

Form Controls

First of all, let’s create components for commonly used 7 form controls. All of the control components are created with in controls folder.

Input

This component renders a textbox, into it you could pass following properties.

  • name – this property is used to name the control to uniquely identify the control.
  • value – value inside the control is assigned through this property.
  • label – label text to be shown along with the control.
  • onChange – a function to be called when there is a change of value inside the control.
  • other – if you’ve passed extra properties. It is retrieved through this property with the help of separator operator.

Above properties are common to all input controls. rest of the properties are

  • variant – an attribute from materil UI, to style the textbox. If there is no value passed for this property default value 'outlined' will be used.

In a page component we’ll be using the Input component as follows

Here you could see the benefit of other object in our component. there is no type property in Input component. even though it will be applied through other object.

Button

Properties associated

  • variant – material UI style for the button, by default it is 'contained'
  • color – material UI color, the default value is 'primary'
  • text – text to be shown inside the button
  • onClick – function to handle the button click event

Checkbox

There is no extra property here. But there is an function convertToDefEventPara we could discuss that later.

RadioGroup

With this component, we’ve to show a list of radio buttons. Along with other properties, an array of entities must be passed with items property corresponding to each radio button and the list of radio button is rendered while looping through the array.

Select

Same as RadioGroup, options of the select control are rendered from options array.

DatePicker

Apart from material UI, for date picker we’ve to install following packages.

  • Material UI Pickers – npm i @material-ui/pickers
  • npm i @date-io/date-fns@1.3.13 date-fns

As mentioned before, convertToDefEventPara function can be discussed later.

Design the Form with React Hook

When it comes to building form in react, there lot of things common to all forms. like

  • react state management for the controls in it
  • function to handle onChange event
  • form reset operation
  • form design style
  • error validation

as per the DRY principle, we are going to create a react hook and a Form component which can re-used for creating forms inside your application. That we can do inside /components/useForm.js.

Don’t worry I’ll explain everything, inside this file we’ve a custom react hook – useForm and a Form component.

  1. useForm Hook
    – it expect a model object(modelObject) containing properties for all form controls with default values in it.
    – using modelObject, we’ve created a state object values, later in page components it will used for storing current values in form controls.
    handleInputChange function can handle form control onChange event.
    the function expect a parameter object e with a target property containing name and value of the control from which onChange event is triggered. Incase of controls like textbox or select we could directly pass the default event parameter to this e parameter. which has same properties as mentioned above. But for some controls like checkbox and datepicker we’ve to create a new object with above properties from their default event parameter. that’s what we’ve done in convertToDefEventPara function of DatePicker and Checkbox.
    resetForm function can handle form reset operation.
    Finally it returns all the state object with their ‘set’ functions and other event handling function back to the caller.
  2. Form component
    The component returns a normal HTML form with some predefined styles applied.
    – with useStyles function and classes object we’ve set the width and margin for inner form controls. This is a material UI way of customizing components, you should replace it accordance with your UI framework. once you define style or behavior(autoComplete) of the form here, you could re-use the same in rest of the components.
    onSubmit : function to handle form submit event.
    children it is a reserved property in react to refer components added in between Form component.
    for eg: In following case, Input and Select components will be there in children property.

Let’s put Everything Together

Let build a form in react with all the component that we’ve created so far. We’ve created an Employee component in pages folder.

First of all let’s look how to import form control components into Employee component.

Instead of Importing each component on separate line, I’ve an idea. Let’s create an index.js file in controls folder.

This new file will export all control component all together. now you could import them with single line

Now let’s complete Employee component.

Within modelObject, we’ve properties corresponding to all form controls with their default values. which is passed to useForm hook, from that we’ve retrieved state object values and it’s set function and rest of the event handling functions.

arrays genderList and departmentList are used in gender radiogroup and department select control respectively.

Form submit event is handled within handleSubmit function. Now the form should looks like this.

screenshot of form created with this react app.

That’s it!

Video Tutorial

In our YouTube channel, we’ve covered the same topic you could watch the same from here.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top
2 Shares
2 Shares
Share via
Copy link