JSON based dynamic forms with ReactJS
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:-
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.
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.
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