DEV Community

Shubham
Shubham

Posted on

Understanding Formik hooks with use case(complex)

I was working on typical general problem thought worth to share. I am sure if you are working on forms using Formik so you come to this problem definitely. In this article I am sharing via Formik hooks. So I came to know Formik hooks they are amazing :-)

Problem Statement

Problem Statement

As diagram is self explanatory. I would like to explain if you don’t understand. Considering your manager/ designer or whoever ask you to create a form with some design where you have to create Form with accordion i.e Different form can generated based on which accordion we selected. For simplicity I am explaining for one But it can work for for anyone. How we can submit the form by clicking the submit button? And we need to send the value of form which we selected. Hope you got the context. Let’s start !

After going through google and documentation what take my interest is Formik hook it make this thing very simple. Lets understand

Formik hook initialise

In above code we are doing:

  1. Initialising form variable
  2. Assigning what to do when form is submit(onSubmit)
  3. Last but not least assigning useFormik reference to formik variable

Now we can use this formik variable to do anything we want(like validation from parent or child component or submitting from parent or child component). Note : You can do more things from this variable.

Example:

Compelete code

If you don’t understand from above snippet. Its okay. Here you can find live link and you can tinker around with it. I have added all the comments to make things easier for you. If you still don’t understand you can ask in comment section. That’s all for today guys.

Demo of this code hosted here. Feel free to check out.

Thanx for making it to the end!

If you like this article consider buying me a coffee . Cheers!

Top comments (0)