Skip to content

Commit

Permalink
docs: improve time picker example
Browse files Browse the repository at this point in the history
  • Loading branch information
gpbl committed Jun 19, 2023
1 parent 8ac42a5 commit 4eac1d3
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 34 deletions.
2 changes: 1 addition & 1 deletion website/docs/guides/input-fields.md
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ input-range

## Example: Time Selection

DayPicker can also be used alongside a time input field. The time can be directly added to the selected Date.
DayPicker can also be used alongside a time input field, by setting the time to the selected date.

```include-example
input-time
Expand Down
83 changes: 50 additions & 33 deletions website/examples/input-time.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,49 +4,66 @@ import { DayPicker } from 'react-day-picker';

export default function App() {
const [selected, setSelected] = React.useState<Date>();
const [timeValue, setTimeValue] = React.useState<string>('');
const [timeValue, setTimeValue] = React.useState<string>('00:00');

const handleTimeChange: React.ChangeEventHandler<HTMLInputElement> = (
event
) => {
const time = event.target.value;
if (selected) {
const [hours, minutes] = time.split(':').map((str) => parseInt(str, 10));
const newDate = new Date(
selected.getFullYear(),
selected.getMonth(),
selected.getDate(),
hours,
minutes
);
setSelected(newDate);
} else {
const handleTimeChange: React.ChangeEventHandler<HTMLInputElement> = (e) => {
const time = e.target.value;
if (!selected) {
setTimeValue(time);
return;
}
const [hours, minutes] = time.split(':').map((str) => parseInt(str, 10));
const newSelectedDate = new Date(
selected.getFullYear(),
selected.getMonth(),
selected.getDate(),
hours,
minutes
);
setSelected(newSelectedDate);
setTimeValue(time);
};

const handleDaySelect = (date: Date | undefined) => {
if (timeValue && date) {
const [hours, minutes] = timeValue
.split(':')
.map((str) => parseInt(str, 10));
const newDate = new Date(
date.getFullYear(),
date.getMonth(),
date.getDate(),
hours,
minutes
);
setSelected(newDate);
} else {
if (!timeValue || !date) {
setSelected(date);
return;
}
const [hours, minutes] = timeValue
.split(':')
.map((str) => parseInt(str, 10));
const newDate = new Date(
date.getFullYear(),
date.getMonth(),
date.getDate(),
hours,
minutes
);
setSelected(newDate);
};

return (
<div>
<DayPicker mode="single" selected={selected} onSelect={handleDaySelect} />
<input type="time" onChange={handleTimeChange} />
</div>
<>
<DayPicker
mode="single"
selected={selected}
onSelect={handleDaySelect}
footer={
<>
<p>
Pick a time:{' '}
<input
type="time"
value={timeValue}
onChange={handleTimeChange}
/>
</p>
<p>
Selected date: {selected ? selected.toLocaleString() : 'none'}
</p>
</>
}
/>
</>
);
}

0 comments on commit 4eac1d3

Please sign in to comment.