Create multi step form in React with validation.
Today I came up with a tutorial on how to create a multi-step form in React. This is just a simple multi-step form built using react-bootstrap and validator. I created this in my free time to help beginners, don't expect it to be fancy or rich in styling because I have used just simple form components from react-bootstrap and simple validation check from the validator module. So let us start the tutorial.
- Create a simple react application
yarn create react-app multistepform
2. Install some required modules.
yarn add react-bootstrap bootstrap validator
I have used react-bootstrap for creating forms you can use material UI or reactstrap or anything that you like. For validation, I have used a validator module for simple validation you can use formik also.
3. Now open your index.js file and import bootstrap CSS.
4. Now create a components folder inside the src folder and then create a forms folder inside that components folder. Now inside the forms folder create three files.
5. Now open the app.js file from the root of your project and paste the below code inside.
Every bit of code is explained as a comment inside the code.
6. Now open our first form that’s StepOne.js and paste the below code inside that.
Note: I have just created a simple validation using the validator module. If you want you can use any other react validator to validate your form. The form component that has been used can be found here. The name on each input field and event that’s passed on handleFormData is the same as created in the form data state object e.g firstName, lastName, etc. If this is changed, the state of the object will add a new object instead of updating the old object and the form will not work then. The handleFormData on onChange event is saying that hey handleInputData method on app.js I have received a new value from the form just update the formData object with the new value and update the state. Then that new state is received as values and we then are checking that it has got some value and then going to the next step.
7. Now open the StepTwo.js file and paste the below code inside that.
8. Now it’s time to show all the values on our final file that’s Final.js. Paste the below code inside that.
That’s it, this way you can create a simple multi-step form in React. If you want to add more forms then add new files to the switch case and pass the props.
For any query, you can get in touch with me via LinkedIn
Below I have shared the GitHub repository and live code for reference.