简体   繁体   中英

How to set and get a datepicker value using antd with formik?

Here i am creating Datepicker with antd and passing this antd datepicker to formik field.My sample code for Datepicker with antd

    import React from "react";
    import { Form, DatePicker } from "antd"
    import { Field } from "formik";
    import moment from 'moment';

    const FormItem = Form.Item;

    function onChange(date, dateString) {
        console.log(date, dateString);

    }
     const dateFormat = "MM-DD-YYYY"

   // Here i am adding antd error message through DateInput

     const DateInput = ({
            field,
            form: { touched, errors },
            ...props
        }) => {
            const errorMsg = touched[field.name] && errors[field.name]
            const validateStatus = errorMsg ? "error"
                : (touched[field.name] && !errors[field.name]) ? "success"
                    : undefined

            return (
                <div>
                    <FormItem 
                    label={props.label}
                    help={errorMsg}
                    validateStatus={validateStatus}
                    hasFeedback
                   {...props.formitemlayout}>

                    <DatePicker onChange={onChange} defaultPickerValue={moment()}/> 
                    </FormItem>

                </div>
            )
        }
        export default DateInput

i am adding this ant component to formik field component,submit the form using handleSubmit and applying the YUP validations. iam getting a problem was submitting the form iam getting the required validation of DatePicker, and problem is selecting the values of DatePicker iam not getting the value and validation message is displayed after submitting the form.

  class FormikApollo extends React.Component {

        render() {
            const { values, handleSubmit, setFieldValue } = this.props
            return (
                <div align="center">
                    <Form onSubmit={handleSubmit}>
                                <Field
                                    name="username"
                                    label="Name"
                                    placeholder="Enter a Name"
                                    component={TextField}
                                    value={values.username}
                                    formitemlayout={formItemLayout}

                                />
                                <Field
                                    name="email"
                                    label="Email"
                                    placeholder="Enter an Email"
                                    component={TextField}
                                    value={values.email}
                                    formitemlayout={formItemLayout}


                                />

                                <Field
                                    name="password"
                                    label="Password"
                                    type="password"
                                    placeholder="Enter a Password"
                                    component={TextField}
                                    formitemlayout={formItemLayout}
                                />
                                 <Field
                                    name="dateofbirth"
                                    label="dateOfBirth"
                                    type="date"
                                    component={DateInput}
                                    formitemlayout={formItemLayout}
                                    defaultValue={values.dateofbirth}
                                    format={dateFormat} 

                                />


                    <Button type="primary" htmlType="submit">Submit</Button>
                     </Form>  
 )
   }

}

Here i am getting the values through withFormik and submitting the form using handleSubmit. Why iam not getting datepicker value and why validation message is displayed after selecting a datepicker value?

 const FormikApp = (withFormik)({
        mapPropsToValues({ username, email, password, dateofbirth }) {
            return {
                username: username || '',
                email: email || '',
                password: password || '',
                dateofbirth: dateofbirth || ''


            }
        },
        validationSchema: Yup.object().shape({
            username: Yup.string()
                .min(3, "Username must be above 3 characters")
                .required("Username is required"),
            email: Yup.string()
                .email("Invalid Email !!")
                .required("Email is required"),
            password: Yup.string()
                .min(6, "Password must be above 6 characters")
                .required("Password is required"),

            dateofbirth: Yup.string().required("Date is required")



        }),
        handleSubmit(values, { resetForm }) {
            resetForm();
            console.log(values)

        }

    })(FormikApollo)

In your DateInput component try to set value with setFieldValue() method of Formik whether it is valid or not. I believe you can extract it from via: form: { touched, errors, setFieldValue } .

Also check touched items in your form, and make sure that you are changing the value of your date field.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM