Create a dynamic form in React using Hooks
An example of fully dynamic form rendering with Hooks and some other tricks
Hooks were added to React 16.8 and increased the number of features that can be used in functional components. The 2 main additions are lifecycle methods and state management.
The two hooks to achieve that are useEffect()
and useState()
. From these two I will use the latter to showcase state management in a dynamic form.
Let’s start by creating the first building block of our dynamic form, the Input.js
component:
We are using couple of things here:
- Css modules for styling. Thanks to the new react version no webpack configuration is necessary, React will recognize css modules if they are created with the
module.css
tag - Props destructuring for visibility and control over what props are we sending to our
Input.js
. - Setting default props, for instance
placeholder = text
. That means if we are not passing down aplaceholder
prop thetext
will be used as a default. Another benefit of props destructuring.
Secondly we should create our custom Button.js
component:
Another trick we are using here:
- We are passing the
buttonType
down, so that we can create custom styles for different type of buttons we want to have in the application, whileclasses.button
provides the basic style. AsInput.js
, this component can also be further customized.
Now we have our Input.js
and Button.js
components, but before putting them to use we should create a file that will hold our input fields and form structures. Create the following file:
The fields
object holds all possible field that we can add to our forms. This can be easily updated, new fields can be added or the current ones can be customized. I also added a registerForm
and loginForm
examples. We just need to export these arrays so that we can create the dynamic forms!
Next we will create the Form.js
file where we will first use the useState()
hook to manage the information in our form, and will also call all of those components we created to action!
To break down what is happening here:
- The
formStructure
prop is the array we export fromformElements.js
file, in this example eitherregisterForm
orloginForm
. Since these are arrays we can use the map function to iterate through them and render theInput.js
component. These objects hold all the information necessary for ourInput.js
component, so we just need to pass them down. formTitle
andbuttonText
are additional information either used in theForm.js
itself or passed down to our customButton.js
component.- The last bit is the
handleChange()
function where we useuseState()
hook! BothformData
andsetFormData
comes from the hook, however the state is not used in this form, but in the container that renders the form. - In the function we copy the
formData
using the spread operator. This is very important because theuseState()
hook — as opposed tothis.setState()
function — does not automatically merge the state, but replaces it! Therefore we always have to preserve the previous state. - After copying we can set the object either create a new key or update the existing one by using this syntax:
formDataCopy[event.target.name] = event.target.value
That is the basic skeleton for our dynamic form! Now we need a container to render it, where we have the actual logic: managing the state and performing the necessary side effects. I am going to show you an example for rendering registration and login form in a common container I call AuthenticationForm.js
:
You could create two separate components for registration and login forms, but there will be very little difference between them. In the name of re-usability and DRY code we will it in one container. So what is happening here?
const [formData, setFormData] = useState({})
is how we create our initialformData
state, which is empty in the beginning, andsetFormData()
will be the function that will update that state.- The action function takes that
formData
and performs the selected function, which is eitherregisterUser()
orsignInUser()
. This is an authentication solution coming from redux-token-auth because we are using Rails as the API with devise-token-auth. During the function execution we use a switch statement where we can dynamically set that function based on the props we receive. - The last function is the
onSubmit()
, where we perform ouraction()
function, making a HTTP POST request to our API. Upon success reroute to root using the react-router-dom package or catch errors (more error handling functions can be performed there). - As a side-note: the
withRouter
hoc is necessary because we are using therender()
method in the<Route />
component (will be shown later), instead of thecomponent
prop. Because of that thehistory
object is not available by default, we need to wrap the component withwithRouter
if we want to use it.
Finally we need to render the AuthenticationForm.js
somewhere. I use the react-router-dom package to render the forms on different URLs in App.js
:
The loop is completed:
- We import our
registerForm
andloginForm
arrays from ourformElements.js
file which will create our dynamic forms. - We set the action prop which will determine which function will be used,
registerUser()
orsignInUser()
. - We add the
formTitle
andbuttonText
to the forms.
The basic skeleton is ready for further use, after the little lengthy setup it will be much quicker and DRYer to create new forms in our application and without the need for Class components!