ui
ui copied to clipboard
Flexibility to type date in the datepicker
The current date picker doesn't allow manual entry of date to the date picker, which means, to enter my date of birth, it will take me more than a minute to select the date.
@mohammedzamakhan This is just a basic implementation that maybe covers all the states, you should be able to test this and refactor it for your usecase.
export function DatePickerDemo() {
const [stringDate, setStringDate] = React.useState<string>("")
const [date, setDate] = React.useState<Date>()
const [errorMessage, setErrorMessage] = React.useState<string>("")
return (
<Popover>
<div className="relative w-[280px]">
<Input
type="string"
value={stringDate}
onChange={(e) => {
setStringDate(e.target.value)
const parsedDate = new Date(e.target.value)
if (parsedDate.toString() === "Invalid Date") {
setErrorMessage("Invalid Date")
setDate(undefined)
} else {
setErrorMessage("")
setDate(parsedDate)
}
}}
/>
{errorMessage !== "" && (
<div className="absolute bottom-[-1.75rem] left-0 text-red-400 text-sm">
{errorMessage}
</div>
)}
<PopoverTrigger asChild>
<Button
variant={"outline"}
className={cn(
"font-normal absolute right-0 translate-y-[-50%] top-[50%] rounded-l-none",
!date && "text-muted-foreground"
)}
>
<CalendarIcon className="w-4 h-4" />
</Button>
</PopoverTrigger>
</div>
<PopoverContent className="w-auto p-0">
<Calendar
mode="single"
selected={date}
onSelect={(selectedDate) => {
if (!selectedDate) return
setDate(selectedDate)
setStringDate(format(selectedDate, "MM/dd/yyyy"))
setErrorMessage("")
}}
defaultMonth={date}
initialFocus
/>
</PopoverContent>
</Popover>
)
}
I was looking for this too. A datepicker and especially a date range picker where you can't type the date is a fairly inaccessible experience. React Aria has a blog post about date inputs and accessibility that captures this pretty well.
I probably can combine Radix/Shadcn alongside React-Aria's hook API to get my cake and eat it too, but having this built in would of course be much better.