Has anyone successfully made an integration of react-dates DateRangePicker with formik?

流过昼夜 提交于 2019-12-12 10:28:17

问题


I'm confused about how to handle react-dates[DateRangePicker] onDatesChange and onFocusChange because they have two values each. onDatesChange should be able to set multiple values i.e both start date and end date.

I was trying to build a custom wrapper around the daterangepicker with formik.

Check console for errors

`<div className="form-group">
    <label>DatePickerWithFormik</label>
    <Field component={DatePickerWithFormik} name="DatePickerWithFormik" 
    className="form-control" />
</div>`

`export const DatePickerWithFormik = ({ startDateId, endDateId, form: { setFieldValue, setFieldTouched }, field, ...props }) => {
    const [focused, setFocused] = useState(null); // this will be removed
    return(
        <div>
            {/* {console.log('Inside datpicer', field.name)} */}
            <DateRangePicker 
                {...props}
                startDateId="startDateId"
                endDateId="endDateId"
                onDatesChange={(value) => 
                field.onChange(setFieldValue(field.name, value) )}
                onFocusChange={focused => setFocused(focused)}
                focusedInput={focused}
                startDate={field.startDate}
                endDate={field.endDate}
            />
            {/* {console.log(field)} */}
        </div>
    );
};
`
  1. Expected result: Should be able to save both start and end dates in local state and display it on screen.

Refer working link: https://codesandbox.io/s/l72w6n8l0m


回答1:


You need to initialize your form with startDate and endDate:

const formInitialValues = {
  // DatePickerWithFormik: null
  startDate: null,
  endDate: null
}; 

then set the onDatesChange like this: onDatesChange={handleDatesChange} and in the handleDatesChange function update the values:

const handleDatesChange = ({ startDate, endDate }) => {
    setStartDate(startDate);
    setEndDate(endDate);
    setFieldValue("startDate", startDate);
    setFieldValue("endDate", endDate);
  };

Demo: https://codesandbox.io/s/m39w2onqky

Edit:
As you wouldn't use any state you can use the form values property like this:

<DateRangePicker
        startDate={values.startDate}
        startDateId="tata-start-date"
        endDate={values.endDate}
        endDateId="tata-end-date"
        onDatesChange={handleDatesChange}
        focusedInput={focusedInput}
        onFocusChange={focusedInput => setFocusedInput(focusedInput)}
      /> 

working demo: https://codesandbox.io/s/ppv546qxz7



来源:https://stackoverflow.com/questions/55452969/has-anyone-successfully-made-an-integration-of-react-dates-daterangepicker-with

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!