AutorÃa | Ultima modificación | Ver Log |
import React from "react";
import { useState, useEffect, useRef } from "react";
import styled from "styled-components";
import DateTime from "react-datetime";
import moment from "moment";
const DateTimeWrapper = styled.div`
.rdtPicker {
position: absolute;
}
`;
const DateTimeInput = (props) => {
// props destructuring
const {
dateFormat = "YYYY-MM-DD",
timeFormat = false,
viewMode = "days",
onChange,
isValidDate,
settedDate,
} = props;
// states
const [date, setDate] = useState("");
const [formattedDate, setFormattedDate] = useState("");
const [dateTimeOpen, setDateTimeOpen] = useState(false);
// refs
const dateTimeWrapperEl = useRef();
const handleDateChange = (date) => {
// onChange(date.format(dateFormat));
const formattedDate = date.format(dateFormat);
setFormattedDate(formattedDate);
setDate(date);
if (onChange) {
onChange(formattedDate);
}
setDateTimeOpen(false);
};
const handleClickOutside = (e) => {
if (
!dateTimeWrapperEl.current.contains(e.target) &&
dateTimeOpen &&
!RegExp(/\brdt/).test(e.target.className)
) {
setDateTimeOpen(false);
}
};
useEffect(() => {
addEventListener("click", handleClickOutside);
return () => {
removeEventListener("click", handleClickOutside);
};
}, [handleClickOutside]);
useEffect(() => {
setDate(moment(settedDate));
setFormattedDate(moment(settedDate).format(dateFormat));
}, [settedDate]);
let isValidDateProp = {};
if (isValidDate) {
isValidDateProp = { ...isValidDateProp, isValidDate: isValidDate };
}
return (
<React.Fragment>
<DateTimeWrapper ref={dateTimeWrapperEl}>
<input
type="text"
value={moment(date).locale("es").format(dateFormat)}
onClick={(e) => {
e.preventDefault();
setDateTimeOpen(true);
}}
readOnly
/>
<div
style={{
display: dateTimeOpen ? "block" : "none",
}}
>
<DateTime
onChange={(date) => {
handleDateChange(date);
}}
value={date}
dateFormat={dateFormat}
timeFormat={timeFormat}
viewMode={viewMode}
input={false}
// isValidDate={isValidDate}
{...isValidDateProp}
/>
</div>
</DateTimeWrapper>
</React.Fragment>
);
};
export default DateTimeInput;