Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

Sorry, you do not have permission to ask a question, You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please type your username.

Please type your E-Mail.

Please choose an appropriate title for the post.

Please choose the appropriate section so your post can be easily searched.

Please choose suitable Keywords Ex: post, video.

Browse

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Logo Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Logo

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Navigation

  • Home
  • About Us
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • About Us
  • Contact Us
Home/ Questions/Q 6557

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Latest Questions

Author
  • 60k
Author
Asked: November 27, 20242024-11-27T07:39:08+00:00 2024-11-27T07:39:08+00:00

React & Formik Build forms more efficiently

  • 60k

Re-usability and smart design are crucial aspects when building web applications. Planning earlier how the user interface can be broken into components and how components can be reused over different data will reduce spaghetti code and improve the structure of our application.

Building forms can be sometimes challenging. In this tutorial, I will describe how we can design reusable form components with the implementation of formik lightweight library which can help us to speed up the process of building forms for our application.
 

What is Formik

Formik is one of the most popular open-source form libraries for React & React Native. API is well documented and the library lets us choose whether we want to use formik components or utilize it with HTML elements.
Formik takes care of the repetitive and annoying stuff—keeping track of values/errors/visited fields, orchestrating validation, and handling submission—so you don't have to. This means you spend less time wiring up state and change handlers and more time focusing on your business logic.

 
In this example we will build LoginForm with custom react components that will let you build. We utilise Formik to speed up process of building forms and yup to create validation schema. We will handle and display error messages based on our validation schema. We will use nextjs as boilerplate application.
Lets get started!

 

Create next.js project & install dependencies

npx create-next-app nextjs-formik && cd nextjs-formik && npm i formik && npm i yup 
Enter fullscreen mode Exit fullscreen mode

 

Project setup

mkdir components && cd components && mkdir Form && cd Form && touch InputField.js && touch LoginForm.js && FormLabel.js && mkdir validation && cd validation && touch loginSchema.js 
Enter fullscreen mode Exit fullscreen mode

 

We will start with creating InputField and FormLabel components that we will can be reused later in our application.

export const InputField = ({ id, type, style, onChange }) => (   <>     <input id={id} type={type} onChange={onChange} style={style}></input>   </> )  
Enter fullscreen mode Exit fullscreen mode

export const FormLabel = ({ text, style }) => (   <>     <label style={style}>{text}</label>   </> )  
Enter fullscreen mode Exit fullscreen mode

 
 

LoginForm

Now we will create create login form with Formik and our components

import { useFormik } from 'formik' import { InputField } from './InputField' import { FormLabel } from './FormLabel' //import { loginSchema } from './validation/loginSchema'  const LoginForm = () => {   const formik = useFormik({     initialValues: {       email: '',       password: '',     },     //validationSchema: loginSchema,     onSubmit: (values) => {       // Once form submited ex. {Email: 'John@example.com', Password: 'secret'}     },   })   return (     <>       <form id='loginform' onSubmit={formik.handleSubmit}>         <FormLabel text='Email: ' />         <InputField           id='email'           name='email'           onChange={formik.handleChange}           style={{ backgroundColor: 'gray' }}         />         <FormLabel style={{ color: 'red' }} text={formik.errors.email} />         <br></br>         <FormLabel text='Password: ' />         <InputField           id='password'           onChange={formik.handleChange}         />         <FormLabel style={{ color: 'red' }} text={formik.errors.password} />       </form>       <button form='loginform' type='submit'>         Login       </button>     </>   ) }  export default LoginForm  
Enter fullscreen mode Exit fullscreen mode

Excellent! We just created our login form. Now we can add validation using yup a JavaScript schema builder that gives us the power to create custom validation schemas. Yup schemas will let us validate form input and with a combination of formik we can display errors based on rules that we specified in our schema object.
It's a good practice to keep validation schemas in separated files as it improves the readability of code.

Let add validation schema to loginSchema

import * as Yup from 'yup' export const loginSchema = Yup.object().shape({   email: Yup.string().email().required('Required'),   password: Yup.string().required('Required').min(3, 'Too Short!'), }) 
Enter fullscreen mode Exit fullscreen mode

 
Now we can uncomment following

// import { loginSchema } from './validation/loginSchema' // validationSchema: loginSchema 
Enter fullscreen mode Exit fullscreen mode

 

Last part is to go to pages/index.js

import LoginForm from '../components/Form/LoginForm'  export default function Home() {   return (     <div>       <LoginForm />     </div>   ) } 
Enter fullscreen mode Exit fullscreen mode

 
This shows how we speed up form building process and save some time in the future.
By using our simple custom build react components we could extend it even further by adding additional props, styles that suit our needs.
 
 
In the next article, I will cover how we can add tailwind and style our forms.

Hope this tutorial was helpful. Thanks for reading!

github repo

javascriptnextjsreactwebdev
  • 0 0 Answers
  • 2 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

Sidebar

Ask A Question

Stats

  • Questions 4k
  • Answers 0
  • Best Answers 0
  • Users 2k
  • Popular
  • Answers
  • Author

    ES6 - A beginners guide - Template Literals

    • 0 Answers
  • Author

    Understanding Higher Order Functions in JavaScript.

    • 0 Answers
  • Author

    Build a custom video chat app with Daily and Vue.js

    • 0 Answers

Top Members

Samantha Carter

Samantha Carter

  • 0 Questions
  • 20 Points
Begginer
Ella Lewis

Ella Lewis

  • 0 Questions
  • 20 Points
Begginer
Isaac Anderson

Isaac Anderson

  • 0 Questions
  • 20 Points
Begginer

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help

Footer

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise

Querify Question Shop: Explore, ask, and connect. Join our vibrant Q&A community today!

About Us

  • About Us
  • Contact Us
  • All Users

Legal Stuff

  • Terms of Use
  • Privacy Policy
  • Cookie Policy

Help

  • Knowledge Base
  • Support

Follow

© 2022 Querify Question. All Rights Reserved

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.