reactjsonchangeformikreact-datetime

How to add onChange to react-datetime when using formik?


I am trying to add onChangeformik.handleChange() to the react-datetime but it will not work. getting an error. without the onChange() it will work. but it will not work when there is onChange().

without the formik, it works. but I need to add formik also.

const initialValues = {
    enableReinitialize: true,
    validateOnMount: true,
    event_name: "",
    org_name: "",
    event_time: "",
    date_of_the_event: "",
    location: "",
    days_occurs: "",
    event_type: "",
    organizer_name: "",
    org_nic: "",
    cus_email: "",
    cus_con_number: "",
    description: "",
  };
const onSubmit = (values) => {
    console.log("Form Date", values);
};

  const formik = useFormik({
    initialValues,
    onSubmit,
    validationSchema,
  });

                   <Col md="6">
                      <FormGroup>
                        <label>Date of The Event</label>
                        <InputGroup className="input-group-alternative">
                          <InputGroupAddon addonType="prepend">
                            <InputGroupText>
                              <i className="ni ni-calendar-grid-58" />
                            </InputGroupText>
                          </InputGroupAddon>
                          <ReactDatetime
                            inputProps={{
                              placeholder: "Select the Date",
                              name: "date_of_the_event",
                            }}
                            timeFormat={false}
                            onChange={formik.handleChange}
                            onBlur={formik.handleBlur}
                            value={formik.values.date_of_the_event}
                          />
                        </InputGroup>
                      </FormGroup>
                    </Col>

Solution

  • onChange of ReactDatetime return a value (object moment or string). But formik.handleChange recieive an event. So you need to update like this:

    onChange={(value) =>
      formik.handleChange({
        target: {
          name: "date_of_the_event",
          value,
        },
      })
    }
    

    or using setFieldValue

    onChange={(value) =>
      formik.setFieldValue("date_of_the_event", value)
    }