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 2614

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

Author
  • 61k
Author
Asked: November 26, 20242024-11-26T07:03:09+00:00 2024-11-26T07:03:09+00:00

2 ways to build forms using formik with Material UI + Yup!

  • 61k

So, you've diving into the world of React, and, like me, you've found yourself using Formik to simplify form management while also making use of Material UI for attractive user interfaces. In this post, we'll explore two methods to combine these tools, resulting in functional and visually appealing forms.

First things first, make sure you have the libraries required installed:

npm install @mui/material @emotion/react @emotion/styled 
Enter fullscreen mode Exit fullscreen mode

 npm install formik 
Enter fullscreen mode Exit fullscreen mode

 npm install yup 
Enter fullscreen mode Exit fullscreen mode

Let's start with a basic example, laying the foundation for Formik's operation, including initial values, a validation schema, and an onSubmit function. We'll utilize Yup to create a straightforward validation schema.

import * as yup from 'yup'    const initialValues = {     name: '',     surname: '',     phone: '',     age: '',   }    const validationSchema = yup.object({     name: yup.string().required().max(25).min(2),     surname: yup.string().required().max(25).min(2),     phone: yup.string().required(),     age: yup.number()   })    const onSubmit = (data) => {     console.log(data)   }  
Enter fullscreen mode Exit fullscreen mode

Now, let's dive into the first way to integrate Formik with Material UI. We'll access the Formik component within a function to combine it with Material UI:

import { Form, Formik } from "formik";  import { Button, Card, TextField } from "@mui/material";  ...  <Card>   <Formik     initialValues={initialValues}     validationSchema={validationSchema}     onSubmit={onSubmit}   >     {(formik) => (       <Form>         <TextField           label="Name"           name="name"           {...formik.getFieldProps("name")}         />     ...         <Button          variant="contained"          type="submit"          color="success"         >          Submit         </Button>       </Form>         )}   </Formik> </Card> ...   
Enter fullscreen mode Exit fullscreen mode

Using {…formik.getFieldProps(“name”)} simplifies form state management, automatically handling values, onBlur, and onChange events, along with error handling, for the 'name' field.

Next, let's ensure our validation messages appear in Material UI, but only after the user has interacted with the field.

Input field for user name

To achieve this, we can use Formik in conjunction with the Material UI TextField's error and helperText properties:

 ...  <TextField   label="Name"   name="name"   {...formik.getFieldProps("name")}       error={formik.touched.name && !!formik.errors.name}   helperText={formik.touched.name && formik.errors.name} /> ...  
Enter fullscreen mode Exit fullscreen mode

Now, if you require more control over the TextField component, there's another approach to integrate it. You can wrap the TextField with the <Field> component from Formik. This grants you extra resources, such as custom validation functions and access to meta data:

...  // While Formik can handle this validation as well, let's explore a custom approach for the sake of this example :)  const customValidation = (value) => {   const regex = /^[A-Za-zs]+$/; // Regular expression to match alphabets and spaces    if (!value || !regex.test(value)) {     return 'Name should contain only letters and spaces';   }   return undefined; // Validation passed };  ...  <Field name="name" validate={customValidation}>   {({ field, meta }) => (     <TextField       {...field}       label="Name"       error={meta.touched && !!meta.error}       helperText={meta.touched && meta.error}     />   )} </Field>  
Enter fullscreen mode Exit fullscreen mode

That's it for this post. I hope it has helped clarify how to move forward if you are trying to implement these tools together! 😄

reactwebdev
  • 0 0 Answers
  • 1 View
  • 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.