#shadcn date range picker form action

1 messages · Page 1 of 1 (latest)

plucky forumBOT
#

Hi @fresh magnet. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:

#

Based on the information provided in the extracts, there isn't a specific example of using shadcn's Date Range Picker with Next.js form handling. However, the general approach to handling form data in Next.js can be applied.

In your form, you would typically have an event handler for form submission. In this handler, you can access the values of your form fields, including the date range picker, using the FormData API or similar methods.

Here's a general example of how you might handle form submission in Next.js:

async function onSubmit(event: FormEvent<HTMLFormElement>) {
 event.preventDefault()
 
 const formData = new FormData(event.currentTarget)
 const response = await fetch('/api/submit', {
 method: 'POST',
 body: formData,
 })
 
 // Handle response if necessary
 const data = await response.json()
 // ...
}

(Source: Next.js Docs (https://nextjs.org/docs/pages/building-your-application/data-fetching/forms-and-mutations#server-only-form))

In this example, formData.get('fieldName') is used to access the value of a form field. You would replace 'fieldName' with the name of your date range picker field.

Please note that the specifics of how you access the value of the date range picker might depend on the implementation details of the shadcn Date Range Picker component, which isn't covered in the provided extracts.

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:

#

@fresh magnet kapa.ai is still learning and improving, please let us know how it did by reacting below

fresh magnet
#

@plucky forum the date picker has no field name, how can I add one ?

export function DatePickerWithRange({
className,
}: React.HTMLAttributes<HTMLDivElement>) {
const [date, setDate] = React.useState<DateRange | undefined>({
from: new Date(Date.now()),
to: addDays(new Date(Date.now()), 7),
})

return (
    <div className={cn("grid gap-2", className)}>
        <Popover>
            <PopoverTrigger asChild>
                <Button
                    id="date"
                    variant={"outline"}
                    className={cn(
                        "w-[300px] justify-start text-left font-normal",
                        !date && "text-muted-foreground"
                    )}
                >
                    <IoCalendarOutline className="mr-2 h-4 w-4" />
                    {date?.from ? (
                        date.to ? (
                            <>
                                {format(date.from, "LLL dd, y")} -{" "}
                                {format(date.to, "LLL dd, y")}
                            </>
                        ) : (
                            format(date.from, "LLL dd, y")
                        )
                    ) : (
                        <span>Pick a date</span>
                    )}
                </Button>
            </PopoverTrigger>
            <PopoverContent className="w-auto p-0" align="start">
                <Calendar
                    initialFocus
                    mode="range"
                    defaultMonth={date?.from}
                    selected={date}
                    onSelect={setDate}
                    numberOfMonths={2}
                />
            </PopoverContent>
        </Popover>
    </div>
)

}

plucky forumBOT
#

Let me check the knowledge base for you. One moment! :books:

#

The DatePickerWithRange component you've provided doesn't include a form field that can be directly submitted with a form. Instead, it manages its own state with the useState hook.

To integrate this with a form, you could lift the state up to the parent component (in this case, TripForm). This would allow you to include the selected date range when you submit the form.

Here's a simplified example of how you might do this:

export default async function TripForm() {
    const initialState: any = {
        errors: {},
        message: '',
    }

    const [state, formAction] = useFormState(handleTripForm, initialState)
    const [date, setDate] = React.useState<DateRange | undefined>({
        from: new Date(Date.now()),
        to: addDays(new Date(Date.now()), 7),
    })

    async function onSubmit(event: FormEvent<HTMLFormElement>) {
        event.preventDefault()

        // Include the date range when you submit the form
        const formData = new FormData(event.currentTarget)
        formData.append('dateFrom', date?.from?.toISOString())
        formData.append('dateTo', date?.to?.toISOString())

        const response = await fetch(formAction, {
            method: 'POST',
            body: formData,
        })

        // Handle response if necessary
        const data = await response.json()
        // ...
    }

    return (
        <form className="w-2/5" onSubmit={onSubmit}>
            <Input className="mb-2" type="text" name="tripName" placeholder="Nom du voyage" />
            <Input className="mb-2" type="text" name="tripDescription" placeholder="Description du voyage (optionnelle)" />
            <DatePickerWithRange className="mb-2" date={date} setDate={setDate} />
            <SubmitButton>
                Créer un voyage
            </SubmitButton>
        </form>
    )
}
#

export function DatePickerWithRange({
className,
date,
setDate,
}: React.HTMLAttributes<HTMLDivElement> & { date: DateRange | undefined, setDate: (date: DateRange | undefined) => void }) {
// ...
}


In this example, `DatePickerWithRange` now accepts `date` and `setDate` as props, allowing `TripForm` to control its state. When the form is submitted, the selected date range is included in the form data.

Please note that this is a simplified example and might need to be adjusted based on the specifics of your application.
----------------------
Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:
----------------------