85 lines
2.1 KiB
JavaScript
85 lines
2.1 KiB
JavaScript
import { useEffect, useRef } from "react";
|
|
import { useController } from "react-hook-form";
|
|
|
|
|
|
const DatePicker = ({
|
|
name,
|
|
control,
|
|
placeholder = "DD-MM-YYYY",
|
|
className = "",
|
|
allowText = false,
|
|
maxDate, // removed default new Date()
|
|
minDate,
|
|
...rest
|
|
}) => {
|
|
const inputRef = useRef(null);
|
|
|
|
const {
|
|
field: { onChange, value, ref }
|
|
} = useController({
|
|
name,
|
|
control
|
|
});
|
|
|
|
useEffect(() => {
|
|
if (inputRef.current) {
|
|
flatpickr(inputRef.current, {
|
|
dateFormat: "d-m-Y",
|
|
allowInput: allowText,
|
|
defaultDate: value
|
|
? flatpickr.parseDate(value, "Y-m-d")
|
|
: null,
|
|
maxDate: maxDate ?? undefined, // only applied if passed
|
|
minDate: minDate ? new Date(minDate.split("T")[0]) : undefined,
|
|
onChange: function (selectedDates) {
|
|
if (selectedDates.length > 0) {
|
|
// store in YYYY-MM-DD
|
|
const formatted = flatpickr.formatDate(selectedDates[0], "Y-m-d");
|
|
onChange(formatted);
|
|
} else {
|
|
onChange("");
|
|
}
|
|
},
|
|
...rest
|
|
});
|
|
}
|
|
}, [inputRef, value, allowText, maxDate, minDate, rest, onChange]);
|
|
|
|
return (
|
|
<div className={` position-relative ${className}`}>
|
|
<input
|
|
type="text"
|
|
className="form-control form-control-sm "
|
|
placeholder={placeholder}
|
|
defaultValue={
|
|
value
|
|
? flatpickr.formatDate(
|
|
flatpickr.parseDate(value, "Y-m-d"),
|
|
"d-m-Y"
|
|
)
|
|
: ""
|
|
}
|
|
ref={(el) => {
|
|
inputRef.current = el;
|
|
ref(el);
|
|
}}
|
|
readOnly={!allowText}
|
|
autoComplete="off"
|
|
/>
|
|
|
|
<span
|
|
className="position-absolute top-50 end-0 pe-1 translate-middle-y cursor-pointer"
|
|
onClick={() => {
|
|
if (inputRef.current && inputRef.current._flatpickr) {
|
|
inputRef.current._flatpickr.open();
|
|
}
|
|
}}
|
|
>
|
|
<i className="bx bx-calendar bx-sm fs-5 text-muted"></i>
|
|
</span>
|
|
</div>
|
|
);
|
|
};
|
|
|
|
export default DatePicker;
|