Files
MattrixwvReactComponents/lib/component/input/date/DateInput.tsx

48 lines
1.1 KiB
TypeScript

import type { DateInputProps } from "$/types/InputTypes";
import clsx from "clsx";
import { type ChangeEvent } from "react";
export default function DateInput({
className,
value,
onChange,
...inputProps
}: Readonly<DateInputProps>){
//Used to translate the string from the input to a date for onChange
const changeDate = (e: ChangeEvent<HTMLInputElement>) => {
const [ year, month, day ] = e.target.value.split("-").map(Number);
const newDate = new Date(year, month - 1, day);
onChange(Number.isNaN(newDate.getTime()) ? undefined : newDate);
};
return (
<input
type="date"
className={clsx(
"border rounded-lg px-2 py-1",
className
)}
value={formatDate(value)}
onChange={changeDate}
{...inputProps}
/>
);
}
//Used to translate the date to a string for the input
function formatDate(date: Date | undefined): string{
if(!date || Number.isNaN(date.getTime())){
return "";
}
const year = date.getFullYear();
const month = String(date.getMonth() + 1).padStart(2, "0");
const day = String(date.getDate()).padStart(2, "0");
return `${year}-${month}-${day}`;
}