DEV Community

Cover image for Best library for Form Handling | React | Part 1
Shubham Tiwari
Shubham Tiwari

Posted on • Updated on

Best library for Form Handling | React | Part 1

Hello everyone today, i will be starting another series for Form handling in React. We are going to use some libraries like formik, yup, tailwindcss to achieve form handling.

CREDITS - https://www.youtube.com/@Codevolution

What is formik?

Formik is an open-source library for managing forms in React applications. It provides a set of tools and utilities that make it easier to handle complex forms and form validation by encapsulating the state management, input tracking, and submission logic. Formik simplifies the process of creating, handling, and validating forms by offering a higher-level abstraction and a more intuitive API compared to manually managing form state using React's built-in state management.

What is Yup?

Yup is a JavaScript library that focuses on simplifying and enhancing form validation in applications, particularly when working with forms in React or other JavaScript frameworks. It provides a declarative and schema-based approach to defining validation rules for various data types, making it easier to validate user input, ensure data integrity, and provide helpful error messages.

What is TailwindCSS?

Tailwind CSS is a popular utility-first CSS framework that helps developers quickly build responsive and visually appealing user interfaces. Unlike traditional CSS frameworks that come with pre-designed components, Tailwind focuses on providing a set of utility classes that can be directly applied to HTML elements to style them.

Getting started...

  • To start our series on form handling, we will create a simple form and style with tailwind classes
import React from 'react'

function DemoForm() {

  return (
    <div className='grid-container'>
      <form className='form-container'>
        <div className='form-control'>
          <label htmlFor='name'>Name</label>
          <div className='relative'>
            <input type='text' id='name' name='name' className='form-input' />
          </div>
        </div>

        <div className='form-control'>
          <label htmlFor='email'>E-mail</label>
          <div className='relative'>
            <input type='email' id='email' name='email' className='form-input' />
          </div>
        </div>

        <div className='form-control'>
          <label htmlFor='company'>Company</label>
          <div className='relative'>
            <input type='text' id='company' name='company' className='form-input'/>
          </div>
        </div>
        <button type='submit' className='form-submit'>Submit</button>
      </form>
    </div>
  )
}

export default DemoForm
Enter fullscreen mode Exit fullscreen mode
  • This is how our form structure gonna look like with 3 fields - name, email and company.
  • It also has a submit button to submit the form and some tailwind classes to style the form.

Formik initialization-

We have to import "useFormik" hook and initialise it with some initial values

import React from 'react'
import { useFormik } from 'formik'

const initialValues = {
  name: 'Shubham',
  email: '',
  company: ''
}

const onSubmit = values => {
  console.log('Form data', values)
}

function DemoForm() {

  const formik = useFormik({
    initialValues,
    onSubmit,
  })

  return (
    <div className='grid-container'>
      <form className='form-container' onSubmit={formik.handleSubmit}>
.
.
//rest of the form is same
Enter fullscreen mode Exit fullscreen mode
  • We have assigned the useFormik hook to a variable and passed 2 things inside it, initial values and a on submit handler
  • Then we have attached the onSubmit handler in Form onSubmit event, remember the handler name is always "formik.handleSubmit", don't change it with the one you have manually created.

Binding Input fields with states

To each input field add these 2 attribute, value and onChange

.
.
<input type='text' id='name' name='name' className='form-input' value={formik.values.name} onChange={formik.handleChange}  />
.
.
<input type='email' id='email' name='email' className='form-input' value={formik.values.email} onChange={formik.handleChange}  />
.
.
<input type='text' id='company' name='company' className='form-input'value={formik.values.company} onChange={formik.handleChange} />
.
.
// rest of the form is same

Enter fullscreen mode Exit fullscreen mode
  • We are handling the onChange event with "formik.handleChange", this also should be same in every input and to control the states, we use the dot notation,"formik.values.fieldname", like "formik.values.name" and "formik.values.email"
  • You can add a console log statement to check the state is changing on typing in the fields or not
.
.
const formik = useFormik({
    initialValues,
    onSubmit,
})

console.log(formik.values) // here
.
.
Enter fullscreen mode Exit fullscreen mode

Final Code -

import React from 'react'
import { useFormik } from 'formik'

const initialValues = {
  name: 'Shubham',
  email: '',
  company: ''
}

const onSubmit = values => {
  console.log('Form data', values)
}

function DemoForm() {

  const formik = useFormik({
    initialValues,
    onSubmit,
  })

  console.log(formik.values)

  return (
    <div className='grid-container'>
      <form className='form-container' onSubmit={formik.handleSubmit}>
        <div className='form-control'>
          <label htmlFor='name'>Name</label>
          <div className='relative'>
            <input type='text' id='name' name='name' className='form-input' value={formik.values.name} onChange={formik.handleChange}  />
          </div>
        </div>

        <div className='form-control'>
          <label htmlFor='email'>E-mail</label>
          <div className='relative'>
            <input type='email' id='email' name='email' className='form-input' value={formik.values.email} onChange={formik.handleChange}  />
          </div>
        </div>

        <div className='form-control'>
          <label htmlFor='company'>Company</label>
          <div className='relative'>
            <input type='text' id='company' name='company' className='form-input'value={formik.values.company} onChange={formik.handleChange} />
          </div>
        </div>
        <button type='submit' className='form-submit'>Submit</button>
      </form>
    </div>
  )
}

export default DemoForm
Enter fullscreen mode Exit fullscreen mode

That's it for this part, in the next part, we will validate errors and show them in UI.

THANK YOU FOR CHECKING THIS POST
You can contact me on -
Instagram - https://www.instagram.com/supremacism__shubh/
LinkedIn - https://www.linkedin.com/in/shubham-tiwari-b7544b193/
Email - shubhmtiwri00@gmail.com

^^You can help me with some donation at the link below Thank youπŸ‘‡πŸ‘‡ ^^
β˜• --> https://www.buymeacoffee.com/waaduheck <--

Also check these posts as well
https://dev.to/shubhamtiwari909/website-components-you-should-know-25nm

https://dev.to/shubhamtiwari909/smooth-scrolling-with-js-n56

https://dev.to/shubhamtiwari909/swiperjs-3802

https://dev.to/shubhamtiwari909/custom-tabs-with-sass-and-javascript-4dej

Top comments (11)

Collapse
 
shubhamtiwari909 profile image
Shubham Tiwari

What I learnt from Formik is that we can implement basic level of form handling with native approach and that should be used but when we encounter complex form handling and validations, Formik could help, and also in my code example I have used Formik hook to implement the functionalities, in later part of series, i will reduce the boiler plate and implement same thing with Formik Components with Almost 50 lines of code for this entire approach including UI, Logic, validation, and Form submitting
Formik is itself created to handle the forms with less headache and more fastly

Collapse
 
shubhamtiwari909 profile image
Shubham Tiwari

Also in later part of the series, I will show some examples, how formik can handle complex validations with less line of code and implementation is also smooth, if we try to implement those functionalities on our own, it will take time and more lines of code
And I think Formik does the same thing behind the scenes which we implement natively

Collapse
 
jimivi8846 profile image
Jimivi

Appreciate your efforts in building this, I do not mean to be disrespectful in any way.

As of 2023, Formik has been deprecated due to a ton of reasons including lack of features (as listed out by @lukeshiru above) and updated security yet the title makes a bold claim of calling it the "best library for forms", I am not sure why this blog was allowed to posted in the first place considering this is one of the best platforms for web dev.

Organizations have already migrated to react hook form and use of Formik is discouraged by any means.

Ref Link for discussion on their GitHub where the maintainers themselves have called it a day for Formik.

Collapse
 
shubhamtiwari909 profile image
Shubham Tiwari

Well I think I can migrate this same code to React hooks form as the syntax is little bit different but rest is same, but just a question for validation part, Yup is good to use or it also has some alternative?

 
shubhamtiwari909 profile image
Shubham Tiwari

Those are the very specific cases and I checked Formik outputs, it does the same thing as we do with vanilla behind the scenes, Apart from that, We use React which uses JS everywhere, so, that also applies to React that we have Javascript so why use React, To save time and writing same logics again in javascript that react can do for us, same with Formik, it somehow helps in doing those things for us behind the scenes which we might do with vanilla approach and also formik and Yup is created specifically for form handling use cases to save time writing the logic and UI completely,
But I also use Vanilla thing for handling pretty much all the stuffs in React and Next JS, It's just in some places Formik can help us handling form efficiently and with less headache for thinking about logics

 
shubhamtiwari909 profile image
Shubham Tiwari

Well I think I am not at the level to see the differences you are mentioning here, i think I have to practice more and need more time to learn these things
😁😁

Thread Thread
 
jimivi8846 profile image
Jimivi

@lukeshiru has literally listed out a ton of flaws/drawbacks which just shows the surface of Formik limitations, if someone just does 10 minutes of research, they can see why Formik should be avoided in 2023 and why react hook forms is a successor to it!

Thread Thread
 
shubhamtiwari909 profile image
Shubham Tiwari

I checked but I saw React hooks has also limitation, it just it is a latest one to handle forms so it is still in use, Formik is kind of depreciated
I was planning to create 8-10 blogs but I will wrap up the series in the part
😁😁

Collapse
 
shubhamtiwari909 profile image
Shubham Tiwari

Thanks @lukeshiru and @jimivi8846
For explaining the stuff , drawbacks and alternatives πŸ™ŒπŸ™Œ

Collapse
 
shubhamtiwari909 profile image
Shubham Tiwari

Yes it is possible but will cover that later in the series

Collapse
 
panayiotisgeorgiou profile image
Panayiotis Georgiou

is it possible to have custom validation on a specific field?