Building better React forms with Formik

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
this video was brought to you by log rocket the front-end performance monitor that records videos of user sessions along with logs and network data surfacing problems and revealing the root cause of every bug tried today at love rocket comm /yt hey everybody my name is Bryce Ayers and I'm a full-stack software engineer specializing in open source software and today we're gonna be learning about formic Formica is a library for react that it helps make forms essentially easier to build otherwise the process is pretty manual so you can check out jerod Palmer comm slash for Mike if you want to see the documentation make sure before we get started that you have no js' installed you can go to no Jaso org install the long-term support version also the editor I'm going to use today is going to be Visual Studio code so if you don't have it already go ahead and download it and then to start our project we're going to use create react app which is just a bootstrap react project created by Facebook so let's go ahead and get started and we'll come over here to our command line make sure you have NPM installed you type - version you'll see it's 6.11 dot three so it should have MPX installed perfect so let's go ahead and create our project of MPX which is just it's like an NPM installer where you don't have to save the files to your system necessarily for the install so I'll type MPX create react app and we'll call it formic tutorial and then depending on your system and your internet connection this may take a few minutes more than likely thirty seconds or less to go ahead and bootstrap the project and I'll pause it here while it's installing all right now that its installed you see it has some commands here that you can run so let's go ahead and CD into the project change directory and I'm gonna open this up in my favorite editor Visual Studio code alright now that we got that open let's go ahead into our source directory here and you should see one called app J s perfect and I'm just going to pull this up the terminal that they have here and we just need to add a couple packages to get started and I'm gonna use yarn for this part of the project since I was recommended by curry react app so say yarn add formic we also need to add styled components for some basic styling of our stuff and we need to add yup so yup will be for form validation part of the joy library perfect now we can run NPM actually excuse me yarn start go to localhost 3000 we see our app running perfect drag that over so now we have a working application but not much to it just yet so let's go ahead and get started here let's create see what we want to build here first let's actually start with some Styles I'm not gonna focus on styling too much for this app just because somebody actually created another file in here call it Styles j/s and we'll say import let me make that a little bigger here there we go import styled from styled components and then let's put this here I'm just gonna pay some stuff in here real quick I think I can minimize this for right now so I'm gonna do is export this variable called styles I don't really need to know the syntax it's just another way you can do your CSS styling but we're gonna have an h1 element I'm just gonna Center it up we're gonna have a form and we're just gonna do display flex have it in a column format just a little margin spacing our error messages we're gonna make them read and then our submit button I just get set to a color blue text white I just gave it some border radius so nothing crazy there we're just going to save that and then I'll import that in here we can go ahead and delete this here we'll import it from Styles basically can get rid of all this here and I'll just put a div for now actually just put nothing or should we just put styles let's do that save that go back over here here parsing there we go come back over refresh should just say test in the top corner perfect alright so what we want to do here is we want to import formic from formic and now inside here to create our formic component and inside our formic component you need a couple things we need to set and so we need to put some initial values and with our initial values for our form will be an object and the form fields I think we want to have here will be name email accepted terms and will say select for special powers so I'll say name will set to an empty string so email set to an empty string say accepted terms so if you had some terms they needed a little checkbox before they went past it you can set it to false and say we need to know their special power yeah we could save that one other thing we need is we need a validation schema so it's like validation schema now what this is gonna be this is actually going to come from yep so what we can do is go import all as yep from yep so if you remember something about yep comes from the joy validation family typically used with trying to think what that nodejs framework is happy happy Jas so happy Jas they do they use a joy which is I guess you up is a derivative of that per se so here we can actually set validation for these form fields so instead of manually in react going ahead and setting name and email checking if it's the string length is whatever we can do that all kind of right here with yep so we can say yep and we say the forum is gonna be an object and our name field you just say yup dot string and then you can just here's the cool part you just start chaining things on so we can say min we'll say three so we'll say it needs to be a minimum of three characters and so then we can provide a custom error message here so say must be at least three characters you know we chained another thing on there we say max let's say 15 15 characters or less and we also want to be required and our custom message will say required nothing crazy there now gotta do the same for email and quickly see forms even with this helper take a long time to do so again this will be a string say email so the emails the validator I will say invalid email address and we'll say dot required now for our accepted terms we'll say yep and this is not gonna be it's not gonna be a string this one will be actually a boolean value don't say required I think if you don't put that required string in there just give you a default I think a lowercase required if I remember correctly perfect and then also one more thing on a chain and so we want to make sure it's actually a certain value so we'll say one of when we can pass an array we'll say true so it has to match one of the values in the array but since we're only passing true essentially you have to set it to true you can't not set it and we can pass an error message just in case so you must accept the terms and conditions and finally our special power field which will be a select drop-down say yup dot string this is just could be a bunch of strings in here we will use that one up again and there's much more to the up library we're just scratching the surface on it you can get some pretty customized validation without having I mean can you only imagine if you had to type this all out by hand I'll say one of let's say what are the superpowers we'll say flight say invisibility and we'll say wealthy bat guy Bruce Wayne or we'll say other then we give it our error message will say invalid special power so not really gonna pop up I mean there's no other way if it's a select you pretty much have to pick one of those so shouldn't really run it too many issues with that one and then we'll just chain a required on there all right so you say that mr. comma there so that looks valid come back over still nothing showing up just yet we got a little more work to do and so what we can also do is we can set our on submit function so this is kind of a callback that will be called when the form gets submitted and so we're gonna set how we want to handle this and so we're gonna say values so the first entry into this callback function is all the values from the form and then there's also some helpers that get pass in here so set submitting and so you can kind of set it to like a loading state essentially with that in a reset form so it's handy after they submit the form maybe you want to go ahead and automatically reset it for the user so they can add another one for example and so for this instead of making the API call just gonna kind of do a quick test here we'll just use set timeout so after a certain amount of time we'll say three seconds it'll go ahead and trigger an alert so we'll pop up I'm gonna do is just print out the values say values null two so they kind of pretty print for us and once we click OK on that let's go ahead and reset the form so we can use that helper and we can set submitting few false and you'll see we use that are we set some logic in our submit button so that way we'll change it from saying submit to saying loading all right so we got that so that's looking pretty good next thing we want to do I just want to create some quick components here for our form helpers so normally you can use some built-in formic components they have or just write them all by hand yourself but this will kind of clean up our body of our component here so I'm gonna create just some custom components for our text field our check spot our check and our select so say const custom text input and little get past and will be the label and we'll just set props in case there's anything else you want to pass in just make it pretty reusable here and then from here what we can do is we can use a hook called use field let me add it here and we can D structure so we'll do field and meta so equals use field and we'll pass it the props now that we have that information from there we can go return and we'll return our actual component so I'm just gonna do an empty that way it does return a div tags it'll just allow us to return a react fragment here and so I will say label so I want to label for our item I'll say HTML 4 since 4 is a reserved word and we'd say props that ID or props name in case there's no ID passed and we'll actually write out the label in between there and then let's give it an input it will say class name equals let's go to arbitrary name text input and here we want to add on any fields essentially so we can use a spread operator and so all these and this objects here will get spread across and applied and will do the same for props because anything's passed in there and override everything else it'll self close that now here's where it gets interesting we want to render out the error for this form essentially so what we can do is we can say meta touched and so this is kind of a helper we get to say has the input field been touched so did it ever a focus and then a and then a blur essentially or trigger eight a focus for the touched and then we want to check for the air and so if this and this are true then we use a ternary operator then we want to show this which will just be a div class name if you remember from our CSS we set we'll call it air and then all we want to render in there is the actual air itself and this will be our error message coming from the yep library that we had down here otherwise if everything looks good we'll just render null so no error message will be displayed so we can save that what I'm gonna do here is I'm just gonna copy this kind of save some time and I'll call this one oops misspelled to there miss case it call this one custom checkbox these are all pretty similar we don't have to change too much here so then here we're gonna say props and we'll say checkbox the past the type and then from there I'd say label just gonna call it this a.classname checkbox so we target that and input it type equals checkbox and then okay then here is a little confusing but and then here we're gonna render children so we need to make sure childrens passed in so it's actually instead of label children will get passed in for this one and clean this up here there we go so we'll pass in basically the text that'll be next to you the check box so this will be used for our accepted terms so we can have a little check box and then next to it whatever texts want to pass in it can say please accept our terms Terms of agreement anything like that so not too much different than what we had before and then finally our custom select is what we need to create and I think this one is about the same remember what was different about this one oh here we go select no it's not an input just be purely a drop-down perfect so I think we're good now to actually start adding stuff to our form so we scroll down here you can see a this is a pretty tedious process now what we're gonna do is we actually use a render prop so if you're not familiar with this essentially it's a function that gets passed along that'll basically give you back in our case some props to render out and that'll the props will actually have some special function calls for us so we can check like is submitting and stuff like that so we type form and form will get imported from forming if I look up here yep there it is got auto importer for us so I can type form and from here let's do an h1 and we'll say sign up to our signup form now at schools now we've kind of cleaned up all the all this text up here that would have been kind of tedious to write a bunch of times we've now written it out now have it easy access now we can use our custom components we've created and if you want to ever style stuff differently make it look different really easy to do from within here so you can build a completely custom form so say custom text input and you pass it a label call it name the name of the input will be just name lowercase type will equal text and our placeholder will say Frank will be our name all right so we got that so now we do another one and here we just got a couple of small changes to make so our label here will be email email the type is going to be email so we validate properly and then we'll just you Frank at the tank comm so I save that boom so we have a pretty simple site and you can see our error messages are currently working so it says it's required even type this is invalid email address which is pretty cool see it must be at least three characters once I type three characters it works if I type too many must be 15 characters or less so making progress so we're almost there let's go ahead and keep chugging along here so now it's at our custom Select field that we wanted to put in there so it's a custom select label equals special power and we'll say name equals special power camel case and now in here we need to pass it some options so this will be for our drop-down so say value equals I'm going to say for the first one select special power I'll just paste this a couple times so our first one would be flight we have first special power next one will be invisibility well ma'am does I misspelled that then wealthy bat guy and finally other let's just update their text that gets rendered here and finally other so I saved that we should come back over and we see our drop-down perfect so you can select something this is it required okay boom and we have uh select our special power flight so finally let's move on to our checkbox here a last form input custom checkbox say name equals accepted terms and you remember our custom checkbox has this children field so essentially gonna pass that in and just render it straight out so whatever is between these tags here it's gonna get rendered out as the text alongside so I accept the terms and conditions of our signup form you know we see it here you can check it and check it check it once you move away though you must accept the terms and conditions it'll let you know give you a little error message awesome so then finally before we close the form out we need our submit button so we come down here type button let's have equals submit so we know it's for the form then here this is kind of cool so we can access that props and type dot is submitting there's a few other helpers in there use a ternary operator to check so we'll say if it is submitting then we want to render the text loading otherwise gonna render the text submit so let me save that let's come back over and it looks like we have a completed form so I can come up here I can type in my name of my email I can select a special power wellthey bad guy save that she was wealthy bad guy and I accept the terms I click Submit it changes to loading and there's all our data so that's all the data we'd send in a payload to the server if we were actually building a signup form connected to a server and then if we did this right we should click OK and the form should reset loading should go back to submit perfect and so this is actually pretty helpful because we get some basic form validation out of the box we get the required they must be at least three characters which this would take forever to write by hand normally in react it just forms in general or just pretty tedious to do especially when you have these kind of unblurred shion's to try to catch all those actions and then render the correct error message at the right time so we click here it shouldn't submit because our form isn't working and so you could add on you know submit handle submit if there's errors you can check for that and render some additional popup message or something like that but it's pretty self-explanatory to the user when you're going through here and you're typing and it says invalid email address as you're typing pretty pretty helpful so that is formic in a nutshell it has some more advanced features more types of form inputs and ways to handle things so I highly recommend checking it out it'll save you a lot of time when you create forums in react thanks for watching take care
Info
Channel: LogRocket
Views: 31,039
Rating: undefined out of 5
Keywords: react, react js, formik tutorial, formik react, react tutorial, web development
Id: 3sXYK60T6Us
Channel Id: undefined
Length: 28min 4sec (1684 seconds)
Published: Wed Apr 01 2020
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.