Forms are extremely important, but often overlooked part of any web application. In this article, I want to show how you can build dynamic forms in React. We will also discuss their practical use cases and hopefully help you build elegant web applications with smart forms.
Companies want to collect information from users, but it’s just as important for that information to be correct. Form validation is the most effective tool to ensure that users submit correct data. Of course it’s not completely foolproof, but validation one of the more important steps to ensure quality of submitted data.
You can create a function yourself that checks input fields every time user submits the form. It should be triggered after the onSubmit() event handler. In the function body, you can use methods like indexOf() to find whether user’s input contains necessary symbols (@ for email) or if it’s longer than the minimum character length.
Unless you’re building a personal project, using a function to validate input fields is not a good approach. Function that does everything you need would be too complex and difficult to read. It’s much better to use a library like Formik, which takes care of form validation for you.
You can also implement visual cues to help users better understand the form. For example, if their input in one of the fields is wrong, you can highlight borders of input fields in red. So it will draw the attention of users. As you may know, ‘red’ is also often a sign of error or something being wrong.
Reset fields after submit
It’s a good practice to clear input fields after user is finished entering their input and wants to submit. This is especially true if user needs to fill out the same form multiple times. We can help them in their task by clearing input fields every time the form is submitted.
Nick at SimpleFrontEnd wrote an excellent article about clearing input fields in React.
In short, you store input field values in the state. Then handle the submit event to reset state values to an empty string or null. It’s that simple.
Redirect after submit
Forms are much more widespread than you might imagine. A sign-in page also has forms – input fields where users have to enter their username and password. Forms come in many different types and sizes. Sometimes you need to redirect users to another page once they submit the form. For example, redirect them to the homepage after they successfully sign in.
To redirect after submit in React, you’re going to need react-router or similar routing library. I personally use react-router and useNavigate() hook from this library. Once again, SimpleFrontEnd has a great guide on how to implement this feature in React:
As you can see, the new react-router version 6 also provides a Navigate custom component. So you are not limited to functional components.