Sometimes when we create a form, there could be a lot of information that we want. If you put all of the fields on one page, probably it could annoy the user and he might leave before finishing the form. If you want to improve the user experience, you can do a multi-step form.

In this article, I will write about how to do a multi-step form in React. It is a sign-up form. In the first step, I will collect the user’s organization information; and then on the second step, I will collect the user’s personal information. And once it is all done, it will show you a success(or failed) message.

We need a container component!

The very intuitive way to solve this problem will be to create three different components to fulfill what I want to do in three steps. That’s true! However, think about that, do I need three IRRELEVANT components? NO!

All these three components are part of my sign-up process and they will share somethings in common. For example, on the second step, it is going to submit the information it gets from BOTH the second and the first component. After submitted, the third component will show you a hint according to if you submit successfully or not.

How do you share all of this information among three different components? The answer is: use a container component!

With a parent component on the top, we can have these advantages:

  1. The parent can contain common methods and variables for all the children components to share by passing them down as props. Therefore, you can keep your code DRY(Don’t repeat yourself)! And it is easier for code maintenance when you need to change a method or variable all three components will use.
  2. Also, when one child changes a parent’s state field, other children will be notified too because they share the same parent! In that way, you don’t have to keep passing the newly entered information around all the components manually, which is very error-prone.
  3. The children components can be written in functional instead of class components. In that way, it will improve the application performance because functional components are just stateless plain JavaScript functions without lifecycle. That saves the time to go through check related to life cycle when it is rendered.

#state-management #programming #javascript #forms #react

Create a multi-step form in React
56.65 GEEK