Integrating a Date and Time Picker in Qwik: A Bridge Between Qwik and React
Qwik integration docs: https://qwik.builder.io/docs/integrations/react/
In my quest to implement a Date and Time picker for an appointment scheduling application, I stumbled upon a minor roadblock – the nascent Qwik ecosystem had yet to offer a ready-made date picker component. However, fortune smiled upon this endeavor when I discovered that the ingenious teams behind Qwik and React had already forged a path. They've crafted qwik-react, a brilliant toolkit that empowers developers to seamlessly incorporate React components within their Qwik applications.
Install dependencies
npm run qwik add react
Define the react component and "qwikify$" it.
/** @jsxImportSource react */
import { qwikify$ } from "@builder.io/qwik-react";
import { AdapterDayjs } from "@mui/x-date-pickers/AdapterDayjs";
import { LocalizationProvider } from "@mui/x-date-pickers/LocalizationProvider";
import { DateTimePicker } from "@mui/x-date-pickers";
import dayjs from "dayjs";
import utc from "dayjs/plugin/utc";
import timezone from "dayjs/plugin/timezone";
dayjs.extend(utc);
dayjs.extend(timezone);
// Set the time in PST timezone
const twoPM = dayjs().tz("America/Los_Angeles").set("hour", 14).startOf("hour");
const fivePM = dayjs()
.tz("America/Los_Angeles")
.set("hour", 17)
.startOf("hour");
const twoPMNextDay = dayjs()
.tz("America/Los_Angeles")
.add(1, "day")
.set("hour", 14)
.startOf("hour");
const MyDateTimePicker = (props: any) => (
<LocalizationProvider dateAdapter={AdapterDayjs}>
<DateTimePicker
{...props}
minTime={twoPM}
maxTime={fivePM}
minDate={dayjs().tz("America/Los_Angeles").add(1, "day")}
maxDate={dayjs().tz("America/Los_Angeles").add(1, "month")}
defaultValue={twoPMNextDay}
timezone="America/Los_Angeles" // Set the timezone to PST
/>
</LocalizationProvider>
);
export const MUIDateTimePicker = qwikify$(MyDateTimePicker, {
eagerness: "visible",
});
Render the react component in your qwik app.
export default component$(() => {
const time = useSignal<string>(
dayjs()
.add(1, "day")
.hour(14)
.minute(0)
.second(0)
.millisecond(0)
.tz("America/Los_Angeles")
.toISOString()
);
return (
<>
<>
<div>
<MUIDateTimePicker
views={["year", "month", "day", "hours"]}
onChange$={(value: Dayjs) => {
time.value = dayjs(value)
.tz("America/Los_Angeles")
.toISOString();
console.log(dt.safeParse(time.value));
}}
label="Pick a date and time"
/>
</div>
</>
);
});