You need to sign in or sign up before continuing.
Newer
Older
import React, { useEffect, useState } from "react";
import "./datevisibilityinput.css";
type DateVisibilityInputProps = {
date?: string; // YYYY-MM-DD
onDateChange: (date?: string) => void;
};
function DateVisibilityInput({ date, onDateChange }: DateVisibilityInputProps) {
const isDate = (date?: string): boolean => {
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
return false;
}
// Format: YYYY-MM-DD
// Try to convert to date and trigger onChange
const splits: string[] = date.split("-", 3);
if (splits.length != 3) {
return false;
}
const year = parseInt(splits[0]);
const month = parseInt(splits[1]);
const day = parseInt(splits[2]);
if (isNaN(day) || isNaN(month) || isNaN(year)) {
return false;
}
return true;
};
const dateToString = (date: Date): string => {
return (
date.getFullYear() +
"-" +
date.getMonth().toString().padStart(2, "0") +
"-" +
date.getDate().toString().padStart(2, "0")
);
};
const initialEditedDate = () => {
return isDate(date) ? date : dateToString(new Date());
};
const [editedDate, setEditedDate] = useState<string>(initialEditedDate());
const [alwaysVisible, setAlwaysVisible] = useState<boolean>(!isDate(date));
useEffect(() => {
setEditedDate(initialEditedDate());
setAlwaysVisible(!isDate(date));
}, [date]);
const updateVisibilityState = (visible: boolean) => {
setAlwaysVisible(visible);
if (alwaysVisible) {
onDateChange(undefined);
} else {
onDateChange(editedDate);
}
};
const handleDateChange = (date?: string) => {
if (isDate(date)) {
setEditedDate(date);
updateVisibilityState(false);
} else {
updateVisibilityState(true);
}
};
return (
<div className="date-input">
<input
id="date-checkbox"
type={"checkbox"}
checked={alwaysVisible}
onChange={(e) => updateVisibilityState(e.target.checked)}
/>
<label htmlFor="date-checkbox">Always visible</label>
{!alwaysVisible && (
<input
type={"date"}
value={editedDate}
onChange={(e) => handleDateChange(e.target.value)}
/>
)}
</div>
);
}
export default DateVisibilityInput;