Date Field
Enables users to input specific dates within a designated field.
<script lang="ts">
import { DateField } from "bits-ui";
</script>
<DateField.Root>
<div class="flex w-full max-w-[280px] flex-col gap-1.5">
<DateField.Label class="block select-none text-sm font-medium"
>Birthday</DateField.Label
>
<DateField.Input
class="flex h-input w-full select-none items-center rounded-input border border-border-input bg-background px-2 py-3 text-sm tracking-[0.01em] text-foreground focus-within:border-border-input-hover focus-within:shadow-date-field-focus hover:border-border-input-hover data-[invalid]:border-destructive "
>
{#snippet children({ segments })}
{#each segments as { part, value }}
<div class="inline-block select-none">
{#if part === "literal"}
<DateField.Segment {part} class="p-1 text-muted-foreground">
{value}
</DateField.Segment>
{:else}
<DateField.Segment
{part}
class="rounded-5px px-1 py-1 hover:bg-muted focus:bg-muted focus:text-foreground focus-visible:!ring-0 focus-visible:!ring-offset-0 aria-[valuetext=Empty]:text-muted-foreground data-[invalid]:text-destructive"
>
{value}
</DateField.Segment>
{/if}
</div>
{/each}
{/snippet}
</DateField.Input>
</div>
</DateField.Root>
import typography from "@tailwindcss/typography";
import animate from "tailwindcss-animate";
import { fontFamily } from "tailwindcss/defaultTheme";
/** @type {import('tailwindcss').Config} */
export default {
darkMode: "class",
content: ["./src/**/*.{html,js,svelte,ts}"],
theme: {
container: {
center: true,
screens: {
"2xl": "1440px",
},
},
extend: {
colors: {
border: {
DEFAULT: "hsl(var(--border-card))",
input: "hsl(var(--border-input))",
"input-hover": "hsl(var(--border-input-hover))",
},
background: {
DEFAULT: "hsl(var(--background) / <alpha-value>)",
alt: "hsl(var(--background-alt) / <alpha-value>)",
},
foreground: {
DEFAULT: "hsl(var(--foreground) / <alpha-value>)",
alt: "hsl(var(--foreground-alt) / <alpha-value>)",
},
muted: {
DEFAULT: "hsl(var(--muted) / <alpha-value>)",
foreground: "hsl(var(--muted-foreground))",
},
dark: {
DEFAULT: "hsl(var(--dark) / <alpha-value>)",
4: "hsl(var(--dark-04))",
10: "hsl(var(--dark-10))",
40: "hsl(var(--dark-40))",
},
accent: {
DEFAULT: "hsl(var(--accent) / <alpha-value>)",
foreground: "hsl(var(--accent-foreground) / <alpha-value>)",
},
destructive: {
DEFAULT: "hsl(var(--destructive) / <alpha-value>)",
},
contrast: {
DEFAULT: "hsl(var(--contrast) / <alpha-value>)",
},
},
fontFamily: {
sans: ["Inter", ...fontFamily.sans],
mono: ["Source Code Pro", ...fontFamily.mono],
alt: ["Courier", ...fontFamily.sans],
},
fontSize: {
xxs: "10px",
},
borderWidth: {
6: "6px",
},
borderRadius: {
card: "16px",
"card-lg": "20px",
"card-sm": "10px",
input: "9px",
button: "5px",
"5px": "5px",
"9px": "9px",
"10px": "10px",
"15px": "15px",
},
height: {
input: "3rem",
"input-sm": "2.5rem",
},
boxShadow: {
mini: "var(--shadow-mini)",
"mini-inset": "var(--shadow-mini-inset)",
popover: "var(--shadow-popover)",
kbd: "var(--shadow-kbd)",
btn: "var(--shadow-btn)",
card: "var(--shadow-card)",
"date-field-focus": "var(--shadow-date-field-focus)",
},
opacity: {
8: "0.08",
},
scale: {
80: ".80",
98: ".98",
99: ".99",
},
},
keyframes: {
"accordion-down": {
from: { height: "0" },
to: { height: "var(--bits-accordion-content-height)" },
},
"accordion-up": {
from: { height: "var(--bits-accordion-content-height)" },
to: { height: "0" },
},
"caret-blink": {
"0%,70%,100%": { opacity: "1" },
"20%,50%": { opacity: "0" },
},
},
animation: {
"accordion-down": "accordion-down 0.2s ease-out",
"accordion-up": "accordion-up 0.2s ease-out",
"caret-blink": "caret-blink 1.25s ease-out infinite",
},
},
plugins: [typography, animate],
};
@import url("https://fonts.googleapis.com/css2?family=Source+Code+Pro:ital,wght@0,400;0,500;0,600;0,700;1,400;1,500;1,600;1,700&display=swap");
@import url("https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600&display=swap");
@tailwind base;
@tailwind components;
@tailwind utilities;
@layer base {
:root {
/* Colors */
--background: 0 0% 100%;
--background-alt: 0 0% 100%;
--foreground: 0 0% 9%;
--foreground-alt: 0 0% 32%;
--muted: 240 5% 96%;
--muted-foreground: 0 0% 9% / 0.4;
--border: 240 6% 10%;
--border-input: 240 6% 10% / 0.17;
--border-input-hover: 240 6% 10% / 0.4;
--border-card: 240 6% 10% / 0.1;
--dark: 240 6% 10%;
--dark-10: 240 6% 10% / 0.1;
--dark-40: 240 6% 10% / 0.4;
--dark-04: 240 6% 10% / 0.04;
--accent: 204 94% 94%;
--accent-foreground: 204 80% 16%;
--destructive: 347 77% 50%;
/* black */
--constrast: 0 0% 0%;
/* Shadows */
--shadow-mini: 0px 1px 0px 1px rgba(0, 0, 0, 0.04);
--shadow-mini-inset: 0px 1px 0px 0px rgba(0, 0, 0, 0.04) inset;
--shadow-popover: 0px 7px 12px 3px hsla(var(--dark-10));
--shadow-kbd: 0px 2px 0px 0px rgba(0, 0, 0, 0.07);
--shadow-btn: 0px 1px 0px 1px rgba(0, 0, 0, 0.03);
--shadow-card: 0px 2px 0px 1px rgba(0, 0, 0, 0.04);
--shadow-date-field-focus: 0px 0px 0px 3px rgba(24, 24, 27, 0.17);
}
.dark {
/* Colors */
--background: 0 0% 5%;
--background-alt: 0 0% 8%;
--foreground: 0 0% 95%;
--foreground-alt: 0 0% 70%;
--muted: 240 4% 16%;
--muted-foreground: 0 0% 100% / 0.4;
--border: 0 0% 96%;
--border-input: 0 0% 96% / 0.17;
--border-input-hover: 0 0% 96% / 0.4;
--border-card: 0 0% 96% / 0.1;
--dark: 0 0% 96%;
--dark-40: 0 0% 96% / 0.4;
--dark-10: 0 0% 96% / 0.1;
--dark-04: 0 0% 96% / 0.04;
--accent: 204 90 90%;
--accent-foreground: 204 94% 94%;
--destructive: 350 89% 60%;
/* white */
--constrast: 0 0% 100%;
/* Shadows */
--shadow-mini: 0px 1px 0px 1px rgba(0, 0, 0, 0.3);
--shadow-mini-inset: 0px 1px 0px 0px rgba(0, 0, 0, 0.5) inset;
--shadow-popover: 0px 7px 12px 3px hsla(0deg 0% 0% / 30%);
--shadow-kbd: 0px 2px 0px 0px rgba(255, 255, 255, 0.07);
--shadow-btn: 0px 1px 0px 1px rgba(0, 0, 0, 0.2);
--shadow-card: 0px 2px 0px 1px rgba(0, 0, 0, 0.4);
--shadow-date-field-focus: 0px 0px 0px 3px rgba(244, 244, 245, 0.1);
}
}
@layer base {
* {
@apply border-border;
}
html {
-webkit-text-size-adjust: 100%;
font-variation-settings: normal;
}
body {
@apply bg-background text-foreground;
font-feature-settings:
"rlig" 1,
"calt" 1;
}
/* Mobile tap highlight */
/* https://developer.mozilla.org/en-US/docs/Web/CSS/-webkit-tap-highlight-color */
html {
-webkit-tap-highlight-color: rgba(128, 128, 128, 0.5);
}
::selection {
background: #fdffa4;
color: black;
}
/* === Scrollbars === */
::-webkit-scrollbar {
@apply w-2;
@apply h-2;
}
::-webkit-scrollbar-track {
@apply !bg-transparent;
}
::-webkit-scrollbar-thumb {
@apply rounded-card-lg !bg-dark-10;
}
::-webkit-scrollbar-corner {
background: rgba(0, 0, 0, 0);
}
/* Firefox */
/* https://developer.mozilla.org/en-US/docs/Web/CSS/scrollbar-color#browser_compatibility */
html {
scrollbar-color: var(--bg-muted);
}
.antialised {
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
}
@layer utilities {
.step {
counter-increment: step;
}
.step:before {
@apply absolute inline-flex h-9 w-9 items-center justify-center rounded-full border-4 border-background bg-muted text-center -indent-px font-mono text-base font-medium;
@apply ml-[-50px] mt-[-4px];
content: counter(step);
}
}
@layer components {
*:not(body):not(.focus-override) {
outline: none !important;
&:focus-visible {
@apply focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-foreground focus-visible:ring-offset-2 focus-visible:ring-offset-background;
}
}
.link {
@apply inline-flex items-center gap-1 rounded-sm font-medium underline underline-offset-4 hover:text-foreground/80 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-foreground focus-visible:ring-offset-2 focus-visible:ring-offset-background;
}
input::-webkit-outer-spin-button,
input::-webkit-inner-spin-button {
-webkit-appearance: none;
margin: 0;
}
/* Firefox */
input[type="number"] {
-moz-appearance: textfield;
}
}
Heads up!
Before diving into this component, it's important to understand how dates/times work in Bits UI. Please read the Dates documentation to learn more!
Overview
The DateField
component is an alternative to the native <input type="date">
element. It provides a more flexible and customizable way to select dates within a designated field.
Structure
<script lang="ts">
import { DateField } from "$lib";
</script>
<DateField.Root>
<DateField.Label>Check-in date</DateField.Label>
<DateField.Input>
{#snippet children({ segments })}
{#each segments as { part, value }}
<DateField.Segment {part}>
{value}
</DateField.Segment>
{/each}
{/snippet}
</DateField.Input>
</DateField.Root>
Reusable Components
It's recommended to use the DateField
primitives to build your own custom date field component that can be used throughout your application.
The following example shows how you might create a reusable MyDateField
component that can be used throughout your application. For style inspiration, reference the featured demo at the top of this page.
<script lang="ts">
import { DateField, type WithoutChildrenOrChild } from "bits-ui";
type Props = WithoutChildrenOrChild<DateField.RootProps> & {
labelText: string;
};
let { value, placeholder, name, ...restProps }: Props = $props();
</script>
<DateField.Root bind:value bind:placeholder {name} {...restProps}>
<DateField.Label>{labelText}</DateField.Label>
<DateField.Input>
{#snippet children({ segments })}
{#each segments as { part, value }}
<DateField.Segment {part}>
{value}
</DateField.Segment>
{/each}
{/snippet}
</DateField.Input>
</DateField.Root>
<script lang="ts">
import { DateField } from "bits-ui";
let {
labelText = "Select a date",
value = $bindable(),
placeholder = $bindable(),
...restProps
}: DateField.RootProps & { labelText: string } = $props();
</script>
<DateField.Root bind:value bind:placeholder {...restProps}>
<div class="flex w-fit min-w-[280px] flex-col gap-1.5">
<DateField.Label class="block select-none text-sm font-medium"
>{labelText}</DateField.Label
>
<DateField.Input
class="flex h-input w-full select-none items-center rounded-input border border-border-input bg-background px-2 py-3 text-sm tracking-[0.01em] text-foreground focus-within:border-border-input-hover focus-within:shadow-date-field-focus hover:border-border-input-hover data-[invalid]:border-destructive "
>
{#snippet children({ segments })}
{#each segments as { part, value }}
<div class="inline-block select-none">
{#if part === "literal"}
<DateField.Segment {part} class="p-1 text-muted-foreground">
{value}
</DateField.Segment>
{:else}
<DateField.Segment
{part}
class="rounded-5px px-1 py-1 hover:bg-muted focus:bg-muted focus:text-foreground focus-visible:!ring-0 focus-visible:!ring-offset-0 aria-[valuetext=Empty]:text-muted-foreground data-[invalid]:text-destructive"
>
{value}
</DateField.Segment>
{/if}
</div>
{/each}
{/snippet}
</DateField.Input>
</div>
</DateField.Root>
import typography from "@tailwindcss/typography";
import animate from "tailwindcss-animate";
import { fontFamily } from "tailwindcss/defaultTheme";
/** @type {import('tailwindcss').Config} */
export default {
darkMode: "class",
content: ["./src/**/*.{html,js,svelte,ts}"],
theme: {
container: {
center: true,
screens: {
"2xl": "1440px",
},
},
extend: {
colors: {
border: {
DEFAULT: "hsl(var(--border-card))",
input: "hsl(var(--border-input))",
"input-hover": "hsl(var(--border-input-hover))",
},
background: {
DEFAULT: "hsl(var(--background) / <alpha-value>)",
alt: "hsl(var(--background-alt) / <alpha-value>)",
},
foreground: {
DEFAULT: "hsl(var(--foreground) / <alpha-value>)",
alt: "hsl(var(--foreground-alt) / <alpha-value>)",
},
muted: {
DEFAULT: "hsl(var(--muted) / <alpha-value>)",
foreground: "hsl(var(--muted-foreground))",
},
dark: {
DEFAULT: "hsl(var(--dark) / <alpha-value>)",
4: "hsl(var(--dark-04))",
10: "hsl(var(--dark-10))",
40: "hsl(var(--dark-40))",
},
accent: {
DEFAULT: "hsl(var(--accent) / <alpha-value>)",
foreground: "hsl(var(--accent-foreground) / <alpha-value>)",
},
destructive: {
DEFAULT: "hsl(var(--destructive) / <alpha-value>)",
},
contrast: {
DEFAULT: "hsl(var(--contrast) / <alpha-value>)",
},
},
fontFamily: {
sans: ["Inter", ...fontFamily.sans],
mono: ["Source Code Pro", ...fontFamily.mono],
alt: ["Courier", ...fontFamily.sans],
},
fontSize: {
xxs: "10px",
},
borderWidth: {
6: "6px",
},
borderRadius: {
card: "16px",
"card-lg": "20px",
"card-sm": "10px",
input: "9px",
button: "5px",
"5px": "5px",
"9px": "9px",
"10px": "10px",
"15px": "15px",
},
height: {
input: "3rem",
"input-sm": "2.5rem",
},
boxShadow: {
mini: "var(--shadow-mini)",
"mini-inset": "var(--shadow-mini-inset)",
popover: "var(--shadow-popover)",
kbd: "var(--shadow-kbd)",
btn: "var(--shadow-btn)",
card: "var(--shadow-card)",
"date-field-focus": "var(--shadow-date-field-focus)",
},
opacity: {
8: "0.08",
},
scale: {
80: ".80",
98: ".98",
99: ".99",
},
},
keyframes: {
"accordion-down": {
from: { height: "0" },
to: { height: "var(--bits-accordion-content-height)" },
},
"accordion-up": {
from: { height: "var(--bits-accordion-content-height)" },
to: { height: "0" },
},
"caret-blink": {
"0%,70%,100%": { opacity: "1" },
"20%,50%": { opacity: "0" },
},
},
animation: {
"accordion-down": "accordion-down 0.2s ease-out",
"accordion-up": "accordion-up 0.2s ease-out",
"caret-blink": "caret-blink 1.25s ease-out infinite",
},
},
plugins: [typography, animate],
};
@import url("https://fonts.googleapis.com/css2?family=Source+Code+Pro:ital,wght@0,400;0,500;0,600;0,700;1,400;1,500;1,600;1,700&display=swap");
@import url("https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600&display=swap");
@tailwind base;
@tailwind components;
@tailwind utilities;
@layer base {
:root {
/* Colors */
--background: 0 0% 100%;
--background-alt: 0 0% 100%;
--foreground: 0 0% 9%;
--foreground-alt: 0 0% 32%;
--muted: 240 5% 96%;
--muted-foreground: 0 0% 9% / 0.4;
--border: 240 6% 10%;
--border-input: 240 6% 10% / 0.17;
--border-input-hover: 240 6% 10% / 0.4;
--border-card: 240 6% 10% / 0.1;
--dark: 240 6% 10%;
--dark-10: 240 6% 10% / 0.1;
--dark-40: 240 6% 10% / 0.4;
--dark-04: 240 6% 10% / 0.04;
--accent: 204 94% 94%;
--accent-foreground: 204 80% 16%;
--destructive: 347 77% 50%;
/* black */
--constrast: 0 0% 0%;
/* Shadows */
--shadow-mini: 0px 1px 0px 1px rgba(0, 0, 0, 0.04);
--shadow-mini-inset: 0px 1px 0px 0px rgba(0, 0, 0, 0.04) inset;
--shadow-popover: 0px 7px 12px 3px hsla(var(--dark-10));
--shadow-kbd: 0px 2px 0px 0px rgba(0, 0, 0, 0.07);
--shadow-btn: 0px 1px 0px 1px rgba(0, 0, 0, 0.03);
--shadow-card: 0px 2px 0px 1px rgba(0, 0, 0, 0.04);
--shadow-date-field-focus: 0px 0px 0px 3px rgba(24, 24, 27, 0.17);
}
.dark {
/* Colors */
--background: 0 0% 5%;
--background-alt: 0 0% 8%;
--foreground: 0 0% 95%;
--foreground-alt: 0 0% 70%;
--muted: 240 4% 16%;
--muted-foreground: 0 0% 100% / 0.4;
--border: 0 0% 96%;
--border-input: 0 0% 96% / 0.17;
--border-input-hover: 0 0% 96% / 0.4;
--border-card: 0 0% 96% / 0.1;
--dark: 0 0% 96%;
--dark-40: 0 0% 96% / 0.4;
--dark-10: 0 0% 96% / 0.1;
--dark-04: 0 0% 96% / 0.04;
--accent: 204 90 90%;
--accent-foreground: 204 94% 94%;
--destructive: 350 89% 60%;
/* white */
--constrast: 0 0% 100%;
/* Shadows */
--shadow-mini: 0px 1px 0px 1px rgba(0, 0, 0, 0.3);
--shadow-mini-inset: 0px 1px 0px 0px rgba(0, 0, 0, 0.5) inset;
--shadow-popover: 0px 7px 12px 3px hsla(0deg 0% 0% / 30%);
--shadow-kbd: 0px 2px 0px 0px rgba(255, 255, 255, 0.07);
--shadow-btn: 0px 1px 0px 1px rgba(0, 0, 0, 0.2);
--shadow-card: 0px 2px 0px 1px rgba(0, 0, 0, 0.4);
--shadow-date-field-focus: 0px 0px 0px 3px rgba(244, 244, 245, 0.1);
}
}
@layer base {
* {
@apply border-border;
}
html {
-webkit-text-size-adjust: 100%;
font-variation-settings: normal;
}
body {
@apply bg-background text-foreground;
font-feature-settings:
"rlig" 1,
"calt" 1;
}
/* Mobile tap highlight */
/* https://developer.mozilla.org/en-US/docs/Web/CSS/-webkit-tap-highlight-color */
html {
-webkit-tap-highlight-color: rgba(128, 128, 128, 0.5);
}
::selection {
background: #fdffa4;
color: black;
}
/* === Scrollbars === */
::-webkit-scrollbar {
@apply w-2;
@apply h-2;
}
::-webkit-scrollbar-track {
@apply !bg-transparent;
}
::-webkit-scrollbar-thumb {
@apply rounded-card-lg !bg-dark-10;
}
::-webkit-scrollbar-corner {
background: rgba(0, 0, 0, 0);
}
/* Firefox */
/* https://developer.mozilla.org/en-US/docs/Web/CSS/scrollbar-color#browser_compatibility */
html {
scrollbar-color: var(--bg-muted);
}
.antialised {
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
}
@layer utilities {
.step {
counter-increment: step;
}
.step:before {
@apply absolute inline-flex h-9 w-9 items-center justify-center rounded-full border-4 border-background bg-muted text-center -indent-px font-mono text-base font-medium;
@apply ml-[-50px] mt-[-4px];
content: counter(step);
}
}
@layer components {
*:not(body):not(.focus-override) {
outline: none !important;
&:focus-visible {
@apply focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-foreground focus-visible:ring-offset-2 focus-visible:ring-offset-background;
}
}
.link {
@apply inline-flex items-center gap-1 rounded-sm font-medium underline underline-offset-4 hover:text-foreground/80 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-foreground focus-visible:ring-offset-2 focus-visible:ring-offset-background;
}
input::-webkit-outer-spin-button,
input::-webkit-inner-spin-button {
-webkit-appearance: none;
margin: 0;
}
/* Firefox */
input[type="number"] {
-moz-appearance: textfield;
}
}
We'll be using this newly created MyDateField
component in the following demos and examples to prevent repeating the same code, so be sure to reference it as you go through the documentation.
Segments
A segment of the DateField
represents a not only a specific part of the date, such as the day, month, year, hour, but can also reference a "literal"
which is typically a separator between the different parts of the date, and varies based on the locale
.
Notice that in the MyDateField
component we created, we're styling the DateField.Segment
components differently based on whether they are a "literal"
or not.
Placeholder
The placeholder
prop for the DateField.Root
component isn't what is displayed when the field is empty, but rather what date our field should start with when the user attempts to cycle through the segments. The placeholder can also be used to set a granularity for the date field, which will determine which type of DateValue
object is used for the value
.
By default, the placeholder
will be set to the current date, and be of type CalendarDate
. However, if we wanted this date field to also allow for selecting a time, we could set the placeholder to a CalendarDateTime
object.
<script lang="ts">
import MyDateField from "$lib/components/MyDateField.svelte";
import { CalendarDateTime } from "@internationalized/date";
</script>
<MyDateField placeholder={new CalendarDateTime(2024, 8, 3, 12, 30)} />
If we're collecting a date from the user where we want the timezone as well, we can use a ZonedDateTime
object instead.
<script lang="ts">
import MyDateField from "$lib/components/MyDateField.svelte";
import { now, getLocalTimeZone } from "@internationalized/date";
</script>
<MyDateField placeholder={now("America/New_York")} />
Leap Years!
If you're creating a date field for something like a birthday, ensure your placeholder is set in a leap year to ensure users born on a leap year will be able to select the correct date.
Managing Placeholder State
Bits UI offers several approaches to manage and synchronize the component's placeholder state, catering to different levels of control and integration needs.
1. Two-Way Binding
For seamless state synchronization, use Svelte's bind:placeholder
directive. This method automatically keeps your local state in sync with the component's internal state.
<script lang="ts">
import { DateField } from "bits-ui";
import { CalendarDateTime } from "@internationalized/date";
let myPlaceholder = $state(new CalendarDateTime(2024, 8, 3, 12, 30));
</script>
<button onclick={() => (myPlaceholder = new CalendarDate(2024, 8, 3))}>
Set placeholder to August 3rd, 2024
</button>
<DateField.Root bind:placeholder={myPlaceholder}>
<!-- ... -->
</DateField.Root>
Key Benefits
- Simplifies state management
- Automatically updates
myPlaceholder
when the internal state changes - Allows external control (e.g., changing the placeholder via a separate button/programmatically)
2. Change Handler
For more granular control or to perform additional logic on state changes, use the onPlaceholderChange
prop. This approach is useful when you need to execute custom logic alongside state updates.
<script lang="ts">
import { DateField } from "bits-ui";
import { CalendarDateTime } from "@internationalized/date";
let myPlaceholder = $state(new CalendarDateTime(2024, 8, 3, 12, 30));
</script>
<DateField.Root
placeholder={myPlaceholder}
onPlaceholderChange={(p) => {
placeholder = p;
}}
>
<!-- ... -->
</DateField.Root>
Use Cases
- Implementing custom behaviors on placeholder change
- Integrating with external state management solutions
- Triggering side effects (e.g., logging, data fetching)
3. Fully Controlled
For complete control over the component's state, use a Function Binding to manage the value state externally.
<script lang="ts">
import { DateField } from "bits-ui";
let myPlaceholder = $state();
</script>
<DateField.Root
bind:placeholder={() => myPlaceholder, (newPlaceholder) => (myPlaceholder = newPlaceholder)}
>
<!-- ... -->
</DateField.Root>
When to Use
- Implementing complex logic
- Coordinating multiple UI elements
- Debugging state-related issues
Note
While powerful, fully controlled state should be used judiciously as it increases complexity and can cause unexpected behaviors if not handled carefully.
For more in-depth information on controlled components and advanced state management techniques, refer to our Controlled State documentation.
Managing Value State
Bits UI offers several approaches to manage and synchronize the component's value state, catering to different levels of control and integration needs.
1. Two-Way Binding
For seamless state synchronization, use Svelte's bind:value
directive. This method automatically keeps your local state in sync with the component's internal state.
<script lang="ts">
import { DateField } from "bits-ui";
import { CalendarDateTime } from "@internationalized/date";
let myValue = $state(new CalendarDateTime(2024, 8, 3, 12, 30));
</script>
<button onclick={() => (myValue = myValue.add({ days: 1 }))}> Add 1 day </button>
<DateField.Root bind:value={myValue}>
<!-- ... -->
</DateField.Root>
Key Benefits
- Simplifies state management
- Automatically updates
myValue
when the internal state changes - Allows external control (e.g., changing the value via a separate button/programmatically)
2. Change Handler
For more granular control or to perform additional logic on state changes, use the onValueChange
prop. This approach is useful when you need to execute custom logic alongside state updates.
<script lang="ts">
import { DateField } from "bits-ui";
import { CalendarDateTime } from "@internationalized/date";
let myValue = $state(new CalendarDateTime(2024, 8, 3, 12, 30));
</script>
<DateField.Root
value={myValue}
onValueChange={(v) => {
value = v.set({ hour: v.hour + 1 });
}}
>
<!-- ... -->
</DateField.Root>
Use Cases
- Implementing custom behaviors on value change
- Integrating with external state management solutions
- Triggering side effects (e.g., logging, data fetching)
3. Fully Controlled
For complete control over the component's state, use a Function Binding to manage the value state externally.
<script lang="ts">
import { DateField } from "bits-ui";
let myValue = $state();
</script>
<DateField.Root bind:value={() => myValue, (newValue) => (myValue = newValue)}>
<!-- ... -->
</DateField.Root>
When to Use
- Implementing complex logic
- Coordinating multiple UI elements
- Debugging state-related issues
Note
While powerful, fully controlled state should be used judiciously as it increases complexity and can cause unexpected behaviors if not handled carefully.
For more in-depth information on controlled components and advanced state management techniques, refer to our Controlled State documentation.
Default Value
Often, you'll want to start the DateField.Root
component with a default value. Likely this value will come from a database in the format of an ISO 8601 string. You can use the parseDate
function from the @internationalized/date
package to parse the string into a CalendarDate
object.
<script lang="ts">
import { DateField } from "bits-ui";
import { parseDate } from "@internationalized/date";
// this came from a database/API call
const date = "2024-08-03";
let value = $state(parseDate(date));
</script>
<DateField.Root {value}>
<!-- ... -->
</DateField.Root>
Now our input is populated with the default value. In addition to the parseDate
function, you can also use parseDateTime
or parseZonedDateTime
to parse the string into a CalendarDateTime
or ZonedDateTime
object respectively.
Validation
Minimum Value
You can set a minimum value for the DateField.Root
component by using the minValue
prop. If a user selects a date that is less than the minimum value, the date field will be marked as invalid.
<script lang="ts">
import MyDateField from "$lib/components/MyDateField.svelte";
import { today, getLocalTimeZone } from "@internationalized/date";
const todayDate = today(getLocalTimeZone());
const yesterday = todayDate.subtract({ days: 1 });
</script>
<MyDateField minValue={todayDate} value={yesterday} />
In the example above, we're setting the minimum value to today, and the default value to yesterday. This causes the date field to be marked as invalid, and we can style it accordingly. If you adjust the date to be greater than the minimum value, the invalid state will be cleared.
Maximum Value
You can set a maximum value for the DateField.Root
component by using the maxValue
prop. If a user selects a date that is greater than the maximum value, the date field will be marked as invalid.
<script lang="ts">
import MyDateField from "$lib/components/MyDateField.svelte";
import { today, getLocalTimeZone } from "@internationalized/date";
const todayDate = today(getLocalTimeZone());
const tomorrow = todayDate.add({ days: 1 });
</script>
<MyDateField maxValue={todayDate} value={tomorrow} />
In the example above, we're setting the maximum value to today, and the default value to tomorrow. This causes the date field to be marked as invalid, and we can style it accordingly. If you adjust the date to be less than the maximum value, the invalid state will be cleared.
Custom Validation
You can use the validate
prop to provide a custom validation function for the date field. This function should return a string or array of strings as validation errors if the date is invalid, or undefined/nothing if the date is valid.
The strings are then passed to the onInvalid
callback, which you can use to display an error message to the user.
<script lang="ts">
import MyDateField from "$lib/components/MyDateField.svelte";
import { CalendarDate, type DateValue } from "@internationalized/date";
const value = new CalendarDate(2024, 8, 2);
function validate(date: DateValue) {
return date.day === 1 ? "Date cannot be the first day of the month" : undefined;
}
function onInvalid(reason: "min" | "max" | "custom", msg?: string | string[]) {
if (reason === "custom") {
if (typeof msg === "string") {
// do something with the error message
console.log(msg);
return;
} else if (Array.isArray(msg)) {
// do something with the error messages
console.log(msg);
return;
}
console.log("The date is invalid");
} else if (reason === "min") {
// let the user know that the date is too early.
console.log("The date is too early.");
} else if (reason === "max") {
// let the user know that the date is too late.
console.log("The date is too late.");
}
}
</script>
<MyDateField {validate} {value} {onInvalid} />
In the example above, we're setting the isDateUnavailable
prop to a function that returns true
for the first day of the month. Try selecting a date that is the first day of the month to see the date field marked as invalid.
Granularity
The granularity
prop sets the granularity of the date field, which determines which segments are rendered in the date field. The granularity
can be set to either 'day'
, 'hour'
, 'minute'
, or 'second'
.
<script lang="ts">
import MyDateField from "$lib/components/MyDateField.svelte";
import { CalendarDateTime } from "@internationalized/date";
const value = new CalendarDateTime(2024, 8, 2, 12, 30);
</script>
<MyDateField granularity="second" {value} />
In the example above, we're setting the granularity to 'second'
, which means that the date field will include an additional segment for the seconds.
Localization
You can use the locale
prop to set the locale of the date field. This will affect the formatting of the date field's segments and placeholders.
<script lang="ts">
import MyDateField from "$lib/components/MyDateField.svelte";
</script>
<MyDateField locale="de" />
API Reference
The root date field component.
Property | Type | Description |
---|---|---|
value $bindable | DateValue | The selected date. Default: undefined |
onValueChange | function | A function that is called when the selected date changes. Default: undefined |
placeholder $bindable | DateValue | The placeholder date, which is used to determine what date to start the segments from when no value exists. Default: undefined |
onPlaceholderChange | function | A function that is called when the placeholder date changes. Default: undefined |
required | boolean | Whether or not the date field is required. Default: false |
validate | function | A function that returns whether or not a date is unavailable. Default: undefined |
onInvalid | function | A callback fired when the date field's value is invalid. Default: undefined |
errorMessageId | string | The Default: undefined |
hourCycle | enum | The hour cycle to use for formatting times. Defaults to the locale preference Default: undefined |
granularity | enum | The granularity to use for formatting the field. Defaults to Default: undefined |
hideTimeZone | boolean | Whether or not to hide the time zone segment of the field. Default: false |
maxValue | DateValue | The maximum valid date that can be entered. Default: undefined |
minValue | DateValue | The minimum valid date that can be entered. Default: undefined |
locale | string | The locale to use for formatting dates. Default: 'en-US' |
disabled | boolean | Whether or not the accordion is disabled. Default: false |
readonly | boolean | Whether or not the field is readonly. Default: false |
readonlySegments | EditableSegmentPart[] | An array of segments that should be readonly, which prevent user input on them. Default: undefined |
children | Snippet | The children content to render. Default: undefined |
The container for the segments of the date field.
Property | Type | Description |
---|---|---|
name | string | The name of the date field used for form submission. If provided, a hidden input element will be rendered alongside the date field. Default: undefined |
ref $bindable | HTMLDivElement | The underlying DOM element being rendered. You can bind to this to get a reference to the element. Default: undefined |
children | Snippet | The children content to render. Default: undefined |
child | Snippet | Use render delegation to render your own element. See Child Snippet docs for more information. Default: undefined |
Data Attribute | Value | Description |
---|---|---|
data-invalid | '' | Present on the element when the field is invalid. |
data-disabled | '' | Present on the element when the field is disabled. |
data-date-field-input | '' | Present on the element. |
A segment of the date field.
Property | Type | Description |
---|---|---|
part required | SegmentPart | The part of the date to render. Default: undefined |
ref $bindable | HTMLDivElement | The underlying DOM element being rendered. You can bind to this to get a reference to the element. Default: undefined |
children | Snippet | The children content to render. Default: undefined |
child | Snippet | Use render delegation to render your own element. See Child Snippet docs for more information. Default: undefined |
Data Attribute | Value | Description |
---|---|---|
data-invalid | '' | Present on the element when the field is invalid |
data-disabled | '' | Present on the element when the field is disabled |
data-readonly | '' | Present on the element when the field or segment is readonly |
data-segment | enum | The part of the date to render. |
data-date-field-segment | '' | Present on the element. |
The label for the date field.
Property | Type | Description |
---|---|---|
ref $bindable | HTMLSpanElement | The underlying DOM element being rendered. You can bind to this to get a reference to the element. Default: undefined |
children | Snippet | The children content to render. Default: undefined |
child | Snippet | Use render delegation to render your own element. See Child Snippet docs for more information. Default: undefined |
Data Attribute | Value | Description |
---|---|---|
data-invalid | '' | Present on the element when the field is invalid |
data-disabled | '' | Present on the element when the field is disabled |
data-date-field-label | '' | Present on the element. |