How to Optimize a React Date Picker
We'll discuss a few small changes that can be made to optimize the date pickers for when a user is to book a certain listing.
Additional Listing DatePicker Changes#
š This module's quiz can be found - here.
šļø Solutions for this module's quiz can be found - here.
The createBooking
mutation is the mutation that is triggered when a user provides payment information and confirms the booking of a listing between certain dates. We have a check be made to confirm the check-out date a user selects is not before the check-in date the user has selected.
We can add an additional check to confirm the user is to never select booking dates that exceed some point in the future. As an example, we can say a user isn't allowed to select dates that are 90 or more days in the future. We can make the server-side validation for this in the createBooking()
resolver function by comparing the difference between today's date and the check-in/check-out dates in milliseconds.
const today = new Date();
const checkInDate = new Date(checkIn);
const checkOutDate = new Date(checkOut);
if (checkInDate.getTime() > today.getTime() + 90 * millisecondsPerDay) {
throw new Error("check in date can't be more than 90 days from today");
}
if (checkOutDate.getTime() > today.getTime() + 90 * millisecondsPerDay) {
throw new Error("check out date can't be more than 90 days from today");
}
millisecondsPerDay
is a constant we can have in the file that represents the number of milliseconds in a day.
const millisecondsPerDay = 86400000;
On the client, we can update the UI of the datepicker elements to have the dates more than 90 days from today be disabled. We can do this in the disabledDate()
function within the <ListingCreateBooking />
component that is used in the disabledDate
prop of the Ant Design <DatePicker />
elements.
const disabledDate = (currentDate?: Moment) => {
if (currentDate) {
const dateIsBeforeEndOfDay = currentDate.isBefore(moment().endOf("day"));
const dateIsMoreThanThreeMonthsAhead = moment(currentDate).isAfter(
moment()
.endOf("day")
.add(90, "days")
);
return (
dateIsBeforeEndOfDay ||
dateIsMoreThanThreeMonthsAhead ||
dateIsBooked(currentDate)
);
} else {
return false;
}
};
This page is a preview of TinyHouse: A Fullstack React Masterclass with TypeScript and GraphQL - Part Two