JSON based dynamic forms with ReactJS

Gagan Sharma
Curofy Engineering
Published in
2 min readDec 10, 2018

React makes it painless to create interactive UI with help of component-based approach. Form rendering and submission are quite simple in React when you have pre-defined fields, but things get a little complicated when there is a need to build a dynamic form, based on the API received from the server.

This guide assumes you have a fair understanding of Javascript and React-JS.

Let’s create Input, Textarea, and a Dropdown as part of the form to get the input from the user.

Below are the respective components:-

Input field
TextArea Field
Select Field with “val” containing the values as dropdown select

So we have created three stateless components, yet you are free to use “state” to further customize the form. Let’s take a sample API response shown below to create a form using the components we have created.

Data used as the state in the component

For handling the input changes, _handleChange prop is going to communicate with parent form component. In the Form component, _handleChange will trigger onChange from the child component and will store the state with respect to the ‘name: value’ of the element.

React State and functions for submitting the form handling the input changes
Form with all form fields loading based on the condition

Since we have not defined the “state” of the Input Form component, we are retrieving using the spread operator (…) in the submitForm. Now we have received the values from the Form in an object to be used to submit the form.

All Done Cheers 😃.

EDIT:- Put a condition for edge case where no input type matches. Render <div></div> or something default you want

--

--

Gagan Sharma
Curofy Engineering

"Frontend Engineer " RivalSystems, ClearTax, Curofy .IIIT Allahabad Alum