Formik 2 Tutorial | React Forms

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments

Just wanted to say that this was a lifesaver for me, thanks!

👍︎︎ 2 👤︎︎ u/hungryharhar 📅︎︎ Dec 03 2019 🗫︎ replies
Captions
I'm gonna be showing you how you can build forms and react using formic - now I want to just jump right into things if you want to fall along exactly with my same setup here I have create react app project up and I just ran this command as you can see right here to create my project and I use the - - type script flag you can ignore that if you just wanna use JavaScript and then I also added a couple dependencies that I'm gonna use so I wanted to show how you can actually do this with that real UI so I'm gonna be using material UI for this so if you want to follow along you can use that but this works with really any UI if you want to use a different UI kit or you have your own components that works too and so I installed for McKenney up along with the material you ilibrary x' alright so that is all I have setup in the project and we're gonna get started from there so the first thing I want to talk about is what we're gonna import from formic so in formic - there's this new component or new hook I should say called use formic and I thought I would be using this but it turns out that it's actually not too useful in most circumstances because it doesn't allow you to wrap your component in a context and just kind of one of the limitations of using a hook so it turns out that I find I'm gonna see myself using the formic component more with formic rather than the hook so we're gonna be using this and we're gonna start by give her this class name we don't need it so I'm gonna wrap not wrap but I'm going to create a format component here and this is a render prop so we're gonna put brackets inside of here and we have a function and then here we are gonna actually display the content of our form inside of this alright so I can have a form and here I want to display a text field and that's going to be coming from material UI and I want to display a button actually we'll come back to the button alright so there's two things that you need to pass into the formant component the first is the initial values prop so these are two required props I should say so this is the first required one and here you just pass in any initial values your form has in my case I'm going to say the first name initial value is going to be Bob and then here I'm going to say on submit is the second prop and this is just a function this function gets called whenever your form is submitted now the first property or a parameter is the data that your form contains when it was submitted the second one is an object you can D structure and you can get access to some extra stuff that form a casts we're going to get come back to this you don't really need to worry about it for now and so I'll just constant log the data when we submit now for Mike is going to give us properties we can access with the parameter of this function here so I can pass in an object and if I hit control space I can see all the things I've available to me the thing that I care about right now is I want to get the values this will give you an object with the current state of the form they have a handle change handle blur and handle submit so we can Hassen handle submit to our form component here so on submit we can pass in our handles submit and then our text field and this is just again coming from material I this could be any text field that you like we're gonna pass in an on change and this is where formic is going to handle the function for this we actually just pass in the handle change here into this and it'll change and then on blur we're gonna pass in the handle blur so it's gonna handle on change and blur and then we also need to pass in a value which is gonna be the current value which we can say values and then we just need to pass in the name of our text field or the value it represents so in this case this text field is going to represent the first name and so we also need to pass in what the name of it is so I'm gonna say first name and this lines up with what you want to be stored in your form ik state alright so let's see this form in action now so I can see I have Bob displayed here and I can type and if you know we have our first input field here and now if I right click inspect I can go to my console and if I type or just hit enter I can see first name Bob hello this is me submitting my form so it called this right here why don't I just put submit that way it's clear now one thing I'm going to also do in this tutorial is just at the bottom here display a pre tag and I'm going to json.stringify the values now the reason why I'm doing this I'm also gonna say null comma two this will format it this will just allow us underneath our form for us to see what the state of our form is as we're doing stuff just helpful for debugging you wouldn't actually display this in your form so here I can see what these values are as I'm typing and whatnot all right cool so the next step is usually you want to add a button to your form to submit it so this is where we will say button and one from material UI submit and all you have to do is make this the type submit for your button and that's that's good to go you don't need to do anything else and it's upset with me I'm not sure why I think it could just be the material UI library expects a different format oh I didn't save it that's all I just forgot to save my thing all right it's happy with me now typescript was just being a little slow alright so we can see my submit button and I can click it and we can see it here also you notice it gave me initial value of Bob and really talked about that but that was what I passed here most forms you are not really going to have an initial value you could just have it like that and while I put this in a div so it's below and alright if we click Submit to submit our form now a common thing you may do is when you're submitting your form usually you have an async request that may take some time to load I send requests to the server something so you can stick that in your on submit and you may want to say disable your button while it's happening so a common thing that you may do is there's this function you can call called set submitting so I can say set submitting is equal to true and then I can make a synced call and then at the end of the async Collins all done right I can say set submitting is false and so what that does is it's going to have this is submitting property here or value it's going to change from two to false so while the form is submitting for example I can disable the button here so I can say disabled is equal to true if we are submitting the form all right you can't really see this but this can be something you can do to help prevent while you're loading something they don't just spam the submit button for whatever reason all right so that's the set submitting and there's some other things in here like for example maybe after you're done with submitting your form you may want to reset it so take a look at the properties you have available to you some of them can be helpful all right now it can be kind of cumbersome to pass and say the value and the on change in onblur for every single field right because I can just copy this and I'm going to change the name to last name and it would change the value to last name and now I have a first name and last name you can change it here and you can see between these two different fields we have kind of some duplications so we can simplify this and the way we can simplify this is with the field component which is from forming all right so I can say field and here I can just pass in the name that I want the field to represent or the value that it matches up with in this case first name and then here I can just specify the type it's gonna be an input field so give that a save now I have two fields here that are mapping to the same value that's totally fine you'll notice they're gonna sync up but notice as I type into this field now it's updating my first name state here so that is pretty nifty so notice how I compare this code to this code we were able to simplify this quite a bit or at least some of the fields we don't have to pass in these now you'll notice with the field though it looked ugly right it doesn't have our nice UI I'm chill UI here so one thing we can do is there's a new prompt on the field here called as and we can pass in the component so it's now I'm going to use our text field component so if you accept a value and on change and on blur for your component you can pass in that component in here like this so it doesn't matter what looks like as long as you take those props so it can get rid of that and I get rid of this so now I have two fields first name and last name which we have two input fields here all right so hello there and I don't know maybe you put a placeholder I actually don't know if placeholders work in material you I will see okay they do so first name and last name and I'm gonna put a div around this so it drops to a new line so you can notice with this place over here I've just passed in a prop and it's gonna pass that prop to the text field there alright so we have a nice simple little form here first name last name and submit like how we did with this field and we simplified having to pass in the handle change they have a little utility for the form as well so you don't have to pass in a handle submit if you want so I care of this and I can use uppercase form here and now I can import form from formic and so that will automatically pass the prop for you underneath the hood so still type and submit the form still works so awesome so that is basically an intro to formic and with the text fields let's talk about some other fields that you may want to do so for example let's start with a check box so I'm going to say field name the check box here is I'm going to call it is tall and the type is going to be a check box and so I'm going to say is tall is false and here you can see all right we have now rendered a check box and now it's an ugly check box again so we can pass in our as field and pass in am to you I check box if we like and yeah okay and let's just bring this down and so we now have a nice material you I check box that is mapped to the is tall property and we can trigger triggered on and off like that so that was pretty easy right now let's do another one let's do cookies which is an array so now cookies here these are all the available cookies that you may want to eat so this is a case where I might want to accept multiple checkboxes because I might want to eat multiple cookies so I'm gonna map cookies the property here the same name goes here and now I'm gonna set a value and I'm just gonna set a div above this so I can see the difference so cookies alright so I'm gonna have a value here this is gonna be chocolate chip now to make another checkbox option you notice I'm going to keep the name exactly the same but change the value so chocolate chip and snickerdoodle I feel like that's probably two words I actually don't even know now let's go with one word and lastly we're interested sugar so I'll give that a save and now we can see I have three here and you can see now my cookies is an empty array and now I can check box this I can now add a chocolate chip to the cookie that I want to eat I can also add snickerdoodle and I now have sugar all right so now I can check off which ones I want to eat but so you notice this is kind of like a checkbox group that I just created here so let's go over how I just create that right so step one and my initial value I this doesn't actually matter what your initial value is but I set as an empty array but you want to make sure this name is going to be lining up with this name here alright so all these have the same name and then to differentiate their option I just changed their values right and then as just we're using armor to do I check box there now maybe we only want them to eat one cookie or maybe we have a new field which let's call it yogurt yogurt and it's gonna be empty by default bring this down and my yogurt filled here I might want to make it a radio button so that's another popular field so I'm going to make this type radio' and the value this is going to be peach and again all I have to do to make this a radio group if you will is to use the same name and then change the value so this is going to be blueberry and this is gonna be Apple I don't know who eats Apple yogurt that sounds kind of weird and here as my property I could leave this blank and we'll just get the default radio buttons and you can notice here right it only lets me select one value peach blueberry apple and if I want to I can do my as property and I can pass on my radio component radio and my radio component is coming from show UI so all you have to do is you have to have a UI component that accepts the properties that a radio accepts so on change checked that sort of thing and I can see we got these guys right here getting select and I can see the difference so that's pretty cool so those are just three different ways now that it's quite easy to set up radios and checkboxes and for Mac to now now the other thing that I want to mention here is usually don't just make radio fields where we can't see the labels but if I go to material UI if I look at how you actually make a dude here a form control label it looks like this I set the value here and then I set the control like that and so this doesn't really map cleanly with our onchange onblur events because we need to also pass in like this random control radio here and we could probably get to work with little odd so what we can do is we can actually create custom fields and we can map these properties so let's see what that looks like so I'm going to create a new field up here which I'm going to call my radio and actually before we get into that let's just render what we want to render so what might what do I want my radio to render is this form control label and so for props I want to take the label which is just going to be a string and that's what I'm going to display here and then the value is going to be now the control that can be like that now the value and all the other variables are going to be custom depending on what our form looks like because we want this to be generic so we're going to take some other props in here that we're kind of going to pass to our form control now I'm just gonna import this from the tree with UI and now to hook into formic we're gonna say use field so this is a form ik hook and here we pass in props so this could be for example the name that we want associated to this and we're gonna see how we use this in a second and so what this will return is a field property and a meta property so if I say field thought I can see all the things I have available to me so now it's gonna pass in a generic value so field value and a generic on change and you can see I can one by one pass in all these different fields or I can simplify my life and I can just loops give you dot dot field so formic is gonna pass in all those props for us that handle updating the fields and then meta has for example whether there's an error in this field and some other metadata we're gonna deal with meta in a second for now we can ignore this property I'm just going to delete it now if you're using typescript so ignore this for JavaScript guys for a second and we want to get the props lined up for so I'm gonna say type my radio props I'm gonna create an object which is has a label which is a string and then the props that we can pass to use field if I hit command and then click on this I can actually see what it expects so it expects you there a string or field attributes I'm gonna use this field attributes so I'm gonna do and field attributes and that's gonna be the props so here I can say react FC is my radio props now this takes the field props passes in you need to pass in it is a generic scene to pass in a value I'm just gonna pass in an empty object here I'm not exactly sure what we're supposed to be passing in but empty object seems to work and wouldn't I click on the type definition for this when we were looking at it you can see the generic that takes here it just stands it together anyway so I didn't really need any extra props but looks like you pass and other props you need here alright so I think what is just telling me it's not used yet nope it's not used yet all right so let's use my radio button here so I'm gonna come down here and now I'm gonna use my radio and actually I don't need to pass it in as this as anymore I just actually render my radio like this so I'm gonna pass in the name which is yogurt the type it's a radio field the value is peach and the labels peach all right and let's see dye mess nope we didn't mess anything up so I'm going to create three properties like this and here's where I'm going to say blueberry and then I'm gonna also do apple alright we'll get rid of these two and so we got our radio group here to decide well flavor yogurt we want let's go check it out and now I can see I have my nice labels on them and I can select the one I want so pretty sweet so whenever you have a field that does not map to your UI component simply this is what you'll do you create a custom component like so and then to get access to any of the formic properties we use the use field alright so let's look at another example of when we may want to use this for example when we want to do validation and show an error so for example let's do it with the first name field here so I'm going to create another one here called my text field and what I want to render is a material UI text field and I want to be able to display errors or any kind of validation so alright so how am I going to do this so we're gonna use our use field component or sorry hook we're gonna have field here we're gonna pass all the field functions to our text field and then we're gonna have a prop here well just props and we can pass that in here because I don't need anything extra like a label for this particular one and then here I'm sorry FC and I'm say field attributes and again this part is for just type script stuff and we have to pass in the same generic to my use field so they're they're happy and so now we're gonna use this meta field here meta so if I click on meta we can see that it has the air and whether it was touched so usually what you'll do is I'll say Const air text is equal to if there's an error and it's been touched aka they've actually typed something in the field usually or they've clicked into the field then we can display the error otherwise just do an empty string and so here I'm going to pass in actually I think my text field I actually forget how you even do let's go just look this up real quick immature UI how you actually display a actually I don't want the component AP I want a component so what I want to do is underneath the text field just display in air so this one so if I click on this I'm thinking I don't just pass in a prompt that I have to do this helper text so air default label looks like I want incorrect entry all right so it's helper text is the field name helper text is going to be my air text and then here I believe air is a boolean that I pass in it looks like it's any I think air let's let's see if I don't pass anything to my error field I think it's just not going to turn red all right but let's not use my my text field and I'm gonna pass these properties in alright so we haven't had any validation to form it yet so we shouldn't see any difference it should just work as a normal text field right now now you notice the placeholder went away it's because we're passing all the props in to use field so we may want to do placeholder like that and pass our placeholder in here all right so we can see our placeholders back I can type normally now let's talk about validation so informing I can say validate and this is a function that takes the current data or the current values in your form called values and you can return an object with any errors that possibly has so usually what I do is you can create a object here called errors and then I can say if values dot first name dot includes Bob I'm gonna say errors dot first name is equal to no Bob and then I return errors so if you didn't find any errors all you do is you pass an empty object back otherwise you put the key of the field that has an error in it and in the message so you can also get what the errors are here so this is another thing that I find helpful to just print out in a pre field and that way I can see what the values are okay so we're gonna be displaying the airs it looks like I have a problem here oh yeah as far as typescript goes I'm just gonna say this is a type any we could make this a record actually let's do some good practices let's make this a record you're using typescript this is probably how I would do it all right so that should be happy with us now so now with my first name here it's totally fine and if I look at the error object here it's empty but notice now I've typed Bob it tells us no Bob here and we can see that this is what our error object looks like so we actually are seeing error here now it's not read and that's where I think I pass in air to make it read so air text so here I'm casting this string to a boolean so it's going to be true or false so if this string is empty it's going to be false there's no error but there is some air text this should return true so now when I type in the first name Bob we get our error message and it's now in red perfect all right so the other thing that I wanted to mention is one way to validate is with this function that you just saw and this we can put arbitrary logic inside of another way is with yep so yep is a library that I'm going to import and yep we can create a schema so it looks something like this I'm not gonna go too much into how yep actually works but just show you how the integration with formic works if you want to learn about it so we're gonna say yep a dot object and here we can pass in keys that match our object here are our values so I'm gonna say first name first name and then I'm gonna display any kind of or I can add any kind of validation I want here so in this case I'm gonna say this is a string it's required and it needs to be a max of ten characters all right we'll give us safe I can also pass in air messages if I want here they also have some default ones I'm going to use so that instead of using this can kompis out by lay command or control / in group comment out and vs code and here I miss a validation schema and just pass this in so validation schema all right so I'll give that a save now come over here now we have some different rules so if I leave this blank it's going to be upset so you can see I clicked in and I clicked out of and so that will trigger the air and also try submitting Beltre there so just to refresh show you again try to submit and it being empty we can see it's required and I can do a really long one first name must be at most in characters so there we go so that it can validate using a yup as well all right to the next thing that I wanted to show you that was validation is how can we handle an array of fields so for example actually let's start with initial values I'd say I want to add some pets and so my pets is going to be an array and let's say this array is not so simple like let's say it has an object inside of it just maybe we have the type of the pet for example maybe a cat and then the name of the pet like Jarvis alright and so I want to be able to add more pets and display form fields for this so they can update the name or the type so let's see how we can do that and I just realized now I'd never went through how to do select fields in formic so this is perfect we'll do a select field with our cat example here alright so the first thing is just there is a component informant called field array and it is a render prop as well so we're gonna do this style of rendering the component and again this was Auto imported from me from formic or I thought it was filled array there we go and here we pass in the prop name so this lines up with the name that we have as our top-level key so in this case the array name is pets so I'm gonna say pets here and this has some array helper functions specifically I control spaces we can see ones like for example move push swap I believe there's a delete or here it is remove as well so there's some helpful fields when you're dealing with erase stuff which we're about to see we are gonna use some of these guys and actually I'm gonna move this field I want this above my cement alright so what I'm gonna do is I'm gonna display a div and I'm going to say values dot pets and I'm just going to map over my pets and for each pet we're gonna display a form field so we're gonna say key and I'm gonna say pet name now I probably wouldn't use the pet name as a key usually but for now this should be fine now inside of here I'm gonna display our my text field and so if we go back up to where we created this before we can use a placeholder if we want a name and a type I don't actually think the type is really necessary in this case also not I think about it I think we just need to pass in really the name and then if we want a placeholder so I'm gonna copy these and we will add it to our text field so in this case my name this is actually going to be kind of special so we're gonna deal with the name in a second and the placeholder I'm just gonna say pet name now here I want to return like this so what I just did there is wrap this in curly braces so now we return like this and this allows us to now put some stuff here because I'm gonna say constant name we're gonna create this here so what the name is is we build it like this we say pets because that is our array key then we say dot and we specify the index should get from mapping and then we say at this index which which name in this case is going to be called name and then we passed that in here and so what that maps to is if we scroll up to our pets so it's going to be pets dot zero dot name maps to Jarvis for example and so that's how you create the mapping for the name to the field all right now let's create another field and I'm going to be using the field component here because we're actually going to be using a select field so I'm gonna say type is select and then I'm gonna say as and here I'm actually going to use the select field from material UI so select and so here I can put the options for my select field in this case they're gonna be menu items that's just how the name that I'm gonna show you I use this so in this case I'm gonna say cat dog or frog alright so this is how you can do a select field and formic so it actually will map everything for you which is quite nice and this is another one where we need to do create a name so here I'm going to I'm just gonna get rid of the Const actually we can just directly pass it in like this that way I don't create two names up there as variables because I can't think of any good names for them alright so we're gonna do this in a similar structure we say pets dot the index and then here this particular one is called type alright so type matches with what I'd called it up here in this case cat alright so let's just see where we are with this so right now looks like I can see my Jarvis name here and I could see that it's a cat I can also pick a different field frog and whatnot I can also type here and something's weird cuz whenever I type it actually loses focus of the field I don't know if it's something with chill UI okay I see why we're getting this problem it's because I use the pet name as a key now that I think about that's actually a terrible key because it changes every time I type a letter so that's what I'm getting this choppiness for so what I'm gonna go ahead and do is give these things IDs and I'm just gonna say math dot random to generate this ID and that way we have a nice stable ID alright so we'll save this come back here no I should be able to change Jarvis to run cool networks perfect all right so I can see here's my pets object in my array of pets now we're gonna add some stuff to be able to add fields to this so let's say a button up here and I'm gonna add this right here add pet and when I click on this I'm gonna call my array helpers and we're gonna call the push and so I'm gonna pass in a empty pet object so here I'm going to say the type is frog by default the name is empty and the ID is equal to a math dot random call and I'm putting the string empty string and plussing it to cast this to a string all right so let's add a pet Ron is a dog and our pet Jimmy and we can see as I'm doing that we can see now our pet object with stuff inside of here and next thing I want to do is just add just a delete button so we're going to add a little X here to use our material material button on click and we're going to say array helpers to bring this up dot remove and pass in the index so now when I click on the X it's going to remove the particular row based on the index all right so let's say we don't care about Jarvis I can click the X and now we can see our pets is totally empty it's at a pet it's at a pet and a B and he's gonna be a cat and I can remove them remember so there you go that is how we can add remove now there's some other array helpers you can use functions I'm not going to go over them that gives you the gist of how you can do this one last thing that I just wanted to touch on was how aromat error messages and errors and validation works on the array fields so for that I could write validation and actually why don't I do this type of validation set the validation schema for now and so for this actually it's really it's actually conte dias to you to do this let's do a validation schema for simplicity sake and I'll show you in the pre tag what it looks like so I'm gonna say pets and I'm gonna say yup dot array of yep objects and the name yep dot string is required so we'll give that safe so I've made this now a required field here so if I try adding pets and I submit you'll notice here it's going to tell me that you have to add those required fields for the pet name now how was I easily able to map all this stuff together with like just me adding the validation here well so what happened there is yupp went ahead and validated it and this is the structure of the air alright so pets it's an array and inside the array here we have objects and name and you basically you see how it matches the same structure as our values so this is how you would structure your air if you wanted to pass back an error for an array and so it's an array of objects and the name and then a string of what the error message is and so what happens is formic automatically uses the names to line this up so it says pets at index one with the name property so you can see it right here this is the name we have four lines up so the name and the error line up and that's how it formic matches them up but there you go that is how you can do error messages with an array as well so one ways to create with you up like this or you can create your own custom object structure like this in the validate function but there you go this video string out quite long but I hope that was a good introduction into formic - and formic in general of how you can do various form things and build different types of forms this is still pretty much an introduction there are several different things you may want to touch on fields and properties help you out but this should give you a good structure to begin trying out formic you
Info
Channel: Ben Awad
Views: 98,897
Rating: 4.9699812 out of 5
Keywords: formik, react, React Forms, Formik 2 Tutorial, formik tutorial
Id: FD50LPJ6bjE
Channel Id: undefined
Length: 40min 21sec (2421 seconds)
Published: Thu Nov 07 2019
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.