Best library for Form Handling | React | Part 1

Shubham Tiwari - Aug 28 '23 - - Dev Community

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

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player