Svelte
Try the live Svelte demo for interactive picker and copy-paste snippets.
Support tier
Full support through Web Components. Register from
universal-datetime-picker/svelte. Use native
onchange handlers, not on:change.
Install + deps
npm install universal-datetime-picker Svelte 5 works with the patterns below. React peers are optional.
Setup
Call defineCustomElements() once in root
+layout.ts or your app entry, import the stylesheet, then
render the custom elements in .svelte files.
Exact import path
import { defineCustomElements, calendarTime } from "universal-datetime-picker/svelte";
import "universal-datetime-picker/style.css";
defineCustomElements(); calendarTime is a Svelte action that only ensures elements
are defined. Most apps can call defineCustomElements() once
at startup and skip the action.
Minimal example
// src/routes/+layout.ts
import { defineCustomElements } from "universal-datetime-picker/svelte";
import "universal-datetime-picker/style.css";
defineCustomElements(); <script lang="ts">
let date = $state<Date | null>(null);
function onChange(e: CustomEvent) {
const next = e.detail;
date = next instanceof Date ? next : null;
}
</script>
<datetime-picker
inline
mode="date"
as-string="false"
onchange={onChange}
></datetime-picker>
<p>Selected: {date ?? "null"}</p> Realistic example
<script lang="ts">
let date = $state<Date | null>(null);
let open = $state(false);
function onChange(e: CustomEvent) {
date = e.detail instanceof Date ? e.detail : null;
}
function onOpenChange(e: CustomEvent) {
open = Boolean(e.detail);
}
</script>
<datetime-picker-input
placeholder="Pick date & time"
as-string="false"
onchange={onChange}
onopenchange={onOpenChange}
></datetime-picker-input>
<datetime-picker-range inline as-string="false"></datetime-picker-range>
<p>Open: {open}</p>
<p>Value: {date?.toLocaleString() ?? "none"}</p> Configuration notes
-
On Svelte 5 custom elements, bind the native
changeCustomEvent withonchange={...}. The legacyon:changedirective does not wire these elements the way you expect. -
Use explicit closing tags.
<datetime-picker />is rejected for non-void custom elements in Svelte 5. -
Attributes remain kebab-case:
as-string,show-seconds, and so on. -
The
calendarTimeaction is available if you preferuse:calendarTimeon a wrapper node instead of an entry import.
Events
-
onchange:event.detailis the selected value -
onopenchange:event.detailis the open boolean
Customization links
Pitfalls
-
Using
on:changeinstead ofonchangesilently misses updates. - Self-closing custom element tags fail the Svelte 5 compiler.
- Registering only inside a leaf component that is never mounted leaves tags undefined. Prefer root layout registration.
Troubleshooting
If events never fire, check onchange spelling and that
defineCustomElements() ran. See Troubleshooting for CSS and SSR
issues.