Build a Multistep Form in NextJs Using react-hook-form and ZOD

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hey friends welcome back to the channel in this video we're going to build a multi-step form in react and xjs we're going to use react hook forms to manage the state we're going to use zot to validate our fields and at the end we're going to add animation to our different steps using frame or motion we're going to end up with something like this if I hit next uh Zod is going to kick in and validate our Fields And if I now fill in the form here I am able to now go to the next step we have a little an here and then we can put in an address a city a province and a zip code and then finish at the complete section or the last step so let's get into this so I've started with a brand new nexj application that's using typescript and tailin CSS it's pretty much what you get out of the box I've only added this pred RC for some formatting options I added this plugin for tailin so it just um also format that's your telin classes I also added this telin plugin for forms because you're dealing with forms I'm using T components inside uh I'll show you for what parts I'm using it but other than this it's pretty much what you get out of the box I've just changed the homepage which is this component that you're seeing responsible for rendering our form here I'm rendering my form right inside of my homepage um and the layout is basically what you get out of the box when you run the script so inside of our homepage all I'm doing is literally rendering this form so let's go inside of this form let me actually close this and close this off let's look at our form from a high level and see what we're doing here so we have this bigger section there is a navigation part up top that you can see containing our steps I'm going to come back to this steps in a second I have a form component and some conditionally rendered segments or steps actually and then down in the bottom I have these two buttons for navigation these are these two buttons that allows you to go back and forth between different steps so let's just start from the steps this is this component that you can see up top that's rendering the corent step or how many steps we have in total for this I have used Telvin components so if you go to Telvin they actually have a paid uh version or UI component Library so if you click on the component you can see different types of components different types of sections uh pages and whatnot down here they have different types of steps that you can render I have selected this top one and all we're doing here really is they're rendering a navigation and an on ordered list and for each list element or for each step we're rendering a button and we're actually mapping over the steps so I've created this array of steps outside of my component where I can Define my steps so Step One is the personal information going back to our page this is a step one it has an ID or a title identifier and a name step two and step three we're going to add to this array later on by actually also including What fields goes in each step so we can then trigger a validation using react hook forms and zot but for now we only have this steps def find we're mapping over each step and for each one we rendering a list element and a button so this button allows you to also navigate between different steps I'm going to disable this later on because actually when you are clicking on this buttons you have to also validate the form to be able to move to the next step I want to keep this tutorial pretty simple so we're going to look at the concept by implementing it inside this next and back or previous buttons but once you understand the concept you can actually apply the same same concept same logic to this buttons I'm going to just uh disable the buttons so therefore the user can only click on this buttons to navigate between different steps of our form now inside of the form before we jump into the form one quick note is that for different steps I'm actually holding a local state called current step starting from zero and for each step we are actually rendering a section inside side of our form so I have this input for the first name here and then the last name and then the email this is our first section our next step actually is the address information where we have the country the state the city the region zip code and whatnot and then the last step is the actual completion where you've submitted your form doing any asynchronous task that you were supposed to do talking to your API to your database and whatnot and then once that succeeds you bring them back into this uh third step or the last step which is the completion now down here for navigation again we have these buttons with some SVG components inside that are going to just help us navigate between different steps so what we're doing is that in one of them we calling this previous function and the other one is calling this next function function so let's see these two functions up top so this next function is going to look at the cor step and if this is lower than the length of our array of steps minus one meaning that we do have another step is going to actually set this current step to the next one or it's going to increment it by one and the previous function is going to then decrement the step but it only does that if we are actually on a step higher than zero so if we are on the very first step the user can't actually go back so with this implementation we have the shell the foundation of what we're going to be working on right now we're not validating we're not actually controlling the states or the values for any of these fields and the user can navigate between all the steps regardless of whether or not they have puted anything here now in the next step let's actually bring in react hook forms and actually add some State and validation to each of these steps or each of the fields inside of our steps okay so instead of you watching me code this step by step I've gone ahead and added react hook forms Zod and some resolvers that will help us to validate our form but I'll will walk you through exactly what I have done now if you're not familiar with react hook forms and Zod I do have a video dedicated for that topic where we dive deeper into actual step-by-step implementing react hook forms and Zod in nextjs so I'm going to include a link in the card somewhere so you can watch that video if you're not comfortable with react hook forms and how it works here the main part or the main purpose of this video is not how react hook forms actually works but how you would actually Implement a multi-step form using react hook forms nonetheless uh one of the main hooks that you would use from this library is the use form hook is going to give you some functions and some objects back that allows you to register your Fields submit your form watch different fields reset your form trigger validation and some form State uh specifically the errors where actually some field has validation errors we're also using Zod to validate the form and we've installed this hook form resolvers and we got the Zar out of it uh like this you can just pass in any form data scheme to your react hook forms so therefore it is going to parse or validate the data submitted by the client from your form against this schema so let's just quickly look at this schema as well this is inside of our lip folder a schema file I've have created this form schema I have a first name which is a string last name email they're pretty much every all of them are string minimum of one is a replacement for the non-empty value which is deprecated this is to just say this is a required field and then any other field that you might have here or any other validation that you want to actually Implement on top of what I had done here you can just do it inside this schema now the good thing about Zod is you can actually use that same schema and infer a type from it so you can use these types later on inside of your hook uh whether it's this use form hook or for your submit Handler function you can use the same type so you infer the types from the same same schema there's no need to duplicate types from your data schema now this process form is a function that we're going to then pass to this handle submit function so the way it works is on your form if I scroll down to our form here we have this handle onsubmit event listener which calls this handle submit this is the function that's uh returned back to you from the use form and then you would send this call back it this is your own call back I called it process form to you can call it whatever you want which receives the data submitted from the form and then does whatever it needs to do here I'm just logging the data and then reset the form uh this is where you would call an external API your on API or maybe use sever actions to actually directly do something on your server site in your database and then uh respond to the client side now as you can see I've updated this next function this is the function that was was supposed to just increment the step to the next step if there was any other step as you can see there are more stuff added to it but before we dive into what we're doing here let me just explain what the idea was behind my implementation so on the first step when the user wants to actually click on the next button I want to validate these three fields that are in Step One how did I go about doing that well first of all in our steps array up top I've added all the fields that are going to be inside of the system that's the first thing that I did now inside of this next button that's going to call this next function on click I'm getting all the fields from that specific step so I'm Step at the corrent step and I'm getting a field this is just literally going to return this array of different steps now use form hook actually exposes a function called trigger this is going to trigger validation you can can uh use it by just calling the function alone without passing any parameters that's going to validate all the fields if you want to validate a specific or a single field you can just pass a string or if you want to validate multiple Fields you can pass an array of strings and that's what I'm doing here so I'm passing in the fields that belongs to that specific step and then I'm passing this shoot Focus this is uh a way for uh the cursor to actually come back focus on the field that has the air if it makes sense you can add it if not can just pass the array of the field and what this does is that it returns a promise and this is going to be true if there is no errors and it's going to be false if it encounters any validation error so on this next button if there is any errors I'm going to return meaning that I'm not going to the next step and if it is true meaning that they actually have inputed the correct information here what's going to happen is that again we're going to check to see if there is actually any other step and then we're going to go to the next step now here inside of this if I'm checking to see if I am the second to the last step so my last step is going to be the completion that's not the step that I want to actually navigate to that's where I actually want to submit my form process the form talk to my API and if this is successful I want to actually go to that third or finish final completion step and this is this second if check what this is doing okay so all we had done to our next function is to validate the fields in each step once the user clicks on this button now the previous step is the same because once you have moved to the next step you can go back to the previous step because you've already validated this step so you can go back but anytime that you want to go to the next step you have to have completed that step that you're currently on and we have to validate that now down here on the form just to quickly review how we would register each field in react hook forums is that we're going to use this register function we're going to pass the name attribute of the field this is the first name so I'm spreading over the props returned from this register there and also I'm including this error object so for the errors if you remember out of the use hook form we got this errors object from the form State this is going to include a property for each of our fields for so for example for the first name there's going to be a property called first name on it and if there's any errors there's going to be a message on it so if there is any message if there is any airor I'm just going to show it here so as easy as that I am just registering every field and showing an airror just underneath every field and that's all we had done to hook our form with react hook forms so now if I move to the second step and actually fill in an address here uh I'm going to the last page if I now inspect the console because I'm just logging the result you can see I have all of my fields from the first name last name State and Street to the city so all the fields from both steps actually locked here and this is actually the function called inside of the next if you remember here we check to see when the next button is clicked if we are actually to the second last step here what I've done is that I am actually calling this same handle submit function that we get back from the use form and I'm passing the process form function that I have to it this is going to return a function and I'm just invoking that this is going to receive the states or the data from the form and then we're going to process it right now I'm just as I mentioned logging them to console this is again where you talk your database called your API end points and whatnot now that's all there is to it to implement a multi-step form using react hook form to control the states and to also trigger validation when the user is trying to navigate between different steps be use Zod here you can use different schema validation tools but the concept and the logic is going to be the same now in the last step we can add some animation to make our form look nicer by bringing in frame or motion okay so I've gone ahead and added frame or motion and the idea is going down to each of our steps let me just close this off so for our form inside of each of our steps now instead of rendering that div we want to render motion. div if you haven't used frame or motion it's pretty easy to animate different elements using frame motion you just just get this motion from the package and you can turn any of your HTML elements like a div to a motion. div and that allows you to pass in extra attributes like initial State and animate State and transitions so therefore frame motion can actually animate your element from your initial state to the animate state with the transition that you define there so let's start by the animation that we're doing on each of the div elements that are literally wrapping our step okay so what I'm doing is that I'm starting from an X this is going to be your translate X so it's going to move the component over on the x axis and opacity of zero and then I'm going to x0 and then opacity of one so the element or the page or the step is going to move from right to left to then uh come to where it's supposed to be at X of zero now before I explain what exactly I'm doing here with this Delta let me just close this off and go to our second step where we're actually doing the exact same thing we having the same transition or translate X from opacity of Z to opacity of one with a transition that allows me to set a duration and an ease function okay now to show you how this would behave if I only had one specific number here so let's say I'm passing in 200 this is going to be 200 pixels and then I'm going to have 200 over here which means each step is going to move from uh translate X 200 off the screen to the zero so now if I refresh the page you can see the Steep moved inside if I now complete this step and go to the uh next one an email so it moves correctly but then now watch what happens when I go back when I go back now again it goes from right to left which doesn't make sense you would want this to have the opposite direction of translate X when you're going back and uh the regular one when you're going forward so basically it has to be reverse of each other if you're going back and if you're going forward now let me bring in that Delta value back and actually show you what happens when we have this Delta basically it's just flipping uh the negative or the direction of this translate X so from one way it comes from the right hand side and if you go back it comes from the left hand side to actually mimic the behavior of you flipping through these pages so now if I put in a name and also an email if I go to the next step we're going to see it navigate from the right but if I go back the previous page actually slides in from the left which is more natural than having just the same type of Animation whether or not you're going back and forth so what is this Delta it's basically the difference between the current page and the previous page so I've added a new state which is the previous page and then a current step or the previous step and the current step and then my Delta is the current step minus the previous step if it's positive I'm moving further or I'm going next if it is negative I'm actually moving back now down here inside of my next function and previous function anytime that I want to set the current step I actually set the actual or the current step to the previous step before changing this state so therefore I'm always holding the value of my current step as the previous step while I'm changing to The Next Step so I can always calculate the delta or the direction of where we're moving if you're going ahead so I can translate from the right and if I'm going back I can translate from the back so this is the only part or the tricky part for adding this animation to our different pages to actually change the direction of our transl X other than that using frame motion and turning your divs into motion dead divs or any other element really to animate them it's pretty simple and that's a wrap for this video folks we implemented a multistep form in react or nextjs using the react hook forms for controlling our form State Z to validate each input on every step and then frame or motion to actually animate between different steps if you have any questions hit me up in the comments like always and I'll see you in the next one bye-bye
Info
Channel: Hamed Bahram
Views: 10,706
Rating: undefined out of 5
Keywords:
Id: lW_0InDuejU
Channel Id: undefined
Length: 20min 31sec (1231 seconds)
Published: Sat Oct 28 2023
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.