行為
選擇後關閉
啟用 shouldCloseOnSelect 後,選擇器會在選取結束日期時自動確認並關閉。
import { useState } from "react";import { DateRangePicker } from "react-date-range-picker-tailwind4";
function ShouldCloseOnSelect() { const [value, setValue] = useState<{ start: Date | null; end: Date | null }>({ start: null, end: null, });
return <DateRangePicker value={value} onChange={setValue} shouldCloseOnSelect />;}多個月份
並排顯示超過預設的兩個月份。
import { useState } from "react";import { DateRangePicker } from "react-date-range-picker-tailwind4";
function MultiMonth() { const [value, setValue] = useState<{ start: Date | null; end: Date | null }>({ start: null, end: null, });
return <DateRangePicker value={value} onChange={setValue} numberOfMonths={3} />;}表單整合
使用 name 屬性來包含用於原生表單提交的隱藏輸入欄位。
💡 Tip
此範例中的提交按鈕樣式是自訂的 —— 本函式庫僅提供日期選擇器。
import { type SubmitEvent, useState } from "react";import { DateRangePicker } from "react-date-range-picker-tailwind4";
function FormIntegration() { const [value, setValue] = useState<{ start: Date | null; end: Date | null }>({ start: null, end: null, });
const handleSubmit = (e: SubmitEvent<HTMLFormElement>) => { e.preventDefault(); const formData = new FormData(e.currentTarget); const start = formData.get("booking"); const end = formData.get("booking-end"); alert( `Submitted range: ${typeof start === "string" ? start : ""} ~ ${typeof end === "string" ? end : ""}`, ); };
return ( <form onSubmit={handleSubmit} style={{ display: "flex", alignItems: "center", gap: 8 }}> <DateRangePicker value={value} onChange={setValue} name="booking" /> <button type="submit" style={{ padding: "6px 14px", border: "1px solid #d1d5db", borderRadius: 6, background: "#3b82f6", color: "#fff", cursor: "pointer", fontSize: 13, }} > Submit </button> </form> );}