Search code examples
reactjsmaterial-uiformikyup

Unable to assign name or ID to DatePicker component for the purpose of Yup validation


I have a Formik form that uses Yup for validation. One of my fields is a Datepicker, but I am unable to integrate it into yup validation.

Below is code which works as far as rendering the component, but as soon as I try wrap <DatePicker/> inside <Field name="date></Field> tags, nothing renders.

    const [fieldDate,setFieldDate] = useState ("");
const dateSchema = Yup.object().shape({
  date: Yup.date().required('Date is required'),
});
   const initialValues = {date:''};
    return (
     
      <div>

        <FormContainer>
             
              <Formik
                initialValues={initialValues}
                //validationSchema={loginValidationSchema}
                validationSchema={dateSchema}
                onSubmit={()=>{console.log ("ok")}}                
              >
                {({ isSubmitting, values, setFieldValue, handleChange, handleBlur, errors, touched }) => (
                <Form className="form">
                  <LocalizationProvider dateAdapter={DateFnsUtils}>
                    <DatePicker
                      label="Date"
                      value={fieldDate}
                      onChange={(newValue:any) => {
                       setFieldDate(newValue);
                      }}
                      renderInput={(params) => <TextField {...params} />}
                    />
                  </LocalizationProvider>
                    <div className="buttonWrapper">          
                          <SubmitButton  type="submit" className="SubmitButton">Submit</SubmitButton>           
                    </div>
                    
                </Form>
             )}
          </Formik>
         
        </FormContainer>
      </div>
         

And here are my imports...I'm including them because I find that there are multiple libraries with the same name from MUI that have different parent directories with different requirements which has somewhat added to my confusion when trying to solve this via online solutions:

import React, { useState} from "react";
import { Formik, Form, Field, ErrorMessage } from "formik";
import {FormContainer,FieldContainer, SubmitButton } from "../GlobalStyle";
import { TextField } from "@mui/material";
import * as Yup from "yup";
import "react-datepicker/dist/react-datepicker.css";

  import { LocalizationProvider } from '@mui/x-date-pickers/LocalizationProvider';
import DateFnsUtils from "@date-io/date-fns";
import { DatePicker } from '@mui/x-date-pickers/DatePicker';

Thanks!


Solution

  • import React from "react";
    import { Formik, Form, Field,  } from "formik";
    import { TextField } from "@mui/material";
    import * as Yup from "yup";
    
    import { LocalizationProvider } from '@mui/x-date-pickers/LocalizationProvider';
    import DateFnsUtils from "@date-io/date-fns";
    import { DatePicker } from '@mui/x-date-pickers/DatePicker';
    
    const dateSchema = Yup.object().shape({
      date: Yup.date().required('Date is required'),
    });
    
    const initialValues = { date: '' };
    
    export const App = () => {
    
      return (
        <div>
          <Formik
            initialValues={initialValues}
            validateOnMount
            validationSchema={dateSchema}
            onSubmit={() => {
              console.log('ok');
            }}
          >
            <Form className="form">
              <Field name="date">
                {({ field, meta, form }) => (
                  <LocalizationProvider dateAdapter={DateFnsUtils}>
                      <DatePicker
                        label="Date"
                        renderInput={(params) => <TextField {...params} />}
                        // Get your date value from your form
                        value={field.value}
                        // Set your date in the form
                        onChange={(date) => form.setFieldValue('date', date)}
                      />
                       {/* Error from yup */}
                      <div>{meta.error}</div>
                  </LocalizationProvider>
                )}
              </Field>
              <div className="buttonWrapper">
                <button type="submit" className="SubmitButton">
                  Submit
                </button>
              </div>
            </Form>
          </Formik>
        </div>
      );
    };
    
    export default App;