부품 입력·예약

예약 양식 reserve-form

상담·방문 예약. 앞으로 14일을 날짜 상자로 늘어놓고 휴무 요일·휴일은 막는다. 날짜를 고르면 그 요일의 시간대가 나오고, 이름·연락처·동의를 확인한 뒤 onSubmit(values) 를 부르고 접수 완료로 바뀐다. 날짜는 화면이 뜬 뒤 계산한다.

설치

shadcn/ui 를 쓰는 Next.js 프로젝트에서 한 줄로 설치됩니다. 파일은 components/bpublish/reserve-form.tsx 로 들어오고, 공통 토큰(base)도 같이 설치됩니다. 테마는 테마에서 하나 고릅니다.

npx shadcn@latest add https://www.bpublish.com/r/reserve-form.json

레지스트리를 등록했다면 npx shadcn@latest add @bpublish/reserve-form · 설치 안내

AI에게 맡기기

Claude Code, Cursor 같은 AI 코딩 도구에 붙여 넣으세요. MCP 서버를 연결해 두면 이름만 말해도 됩니다.

bpublish UI의 예약 양식(reserve-form) 부품으로 만들어 줘. 설치: npx shadcn@latest add https://www.bpublish.com/r/reserve-form.json · 문서: https://www.bpublish.com/designs/components/reserve-form

사용 예시

app/page.tsx
'use client'

import { ReserveForm } from '@/components/bpublish/reserve-form'

export default function Example() {
  return (
    <section className="shell grid gap-12 py-16 md:py-24 lg:grid-cols-12 lg:gap-14">
      <div className="lg:col-span-5">
        <div className="border-t-[3px] border-foreground pt-6">
          <h2 className="heading text-[40px] leading-[1.08] md:text-[60px]">상담 예약</h2>
          <p className="mt-5 text-base leading-[1.8] text-muted-foreground md:text-[17px]">
            레벨 테스트(50분)와 결과 상담(20분)은 무료입니다. 남겨 주신 번호로 하루 안에 연락드립니다.
          </p>
        </div>
        <p className="mt-10 text-sm font-semibold text-muted-foreground">전화로 바로 예약하시려면</p>
        <a href="tel:02-000-0000" className="heading mt-2 block text-[44px] text-primary tabular-nums md:text-[56px]">
          02-000-0000
        </a>
        <img
          src={'/images/consult.webp'}
          alt="상담실에서 강사가 학부모에게 학생의 시험지를 펼쳐 보이며 설명하는 장면"
          className="mt-10 aspect-[3/2] w-full bg-muted object-cover"
        />
      </div>
      <ReserveForm
        className="lg:col-span-7"
        closedWeekdays={[0]}
        holidays={['2026-12-12']}
        slots={['15:00', '16:00', '17:00', '18:00', '19:00', '20:00']}
        slotsByWeekday={{ 6: ['10:00', '11:00', '13:00', '14:00', '15:00', '16:00'] }}
        kinds={['레벨 테스트 + 상담', '설명회 신청', '전화 상담']}
        labels={{ name: '학생 이름' }}
        memo={{ label: '남기실 말씀 (선택)', placeholder: '다니는 학교, 최근 시험 성적 등을 적어 주시면 상담이 빨라집니다.' }}
        agree="상담을 위한 개인정보 수집·이용에 동의합니다. (이름·연락처, 상담 후 6개월 보관)"
        done={{ title: '접수 완료', description: '예약 신청이 접수되었습니다. 하루 안에 남겨 주신 번호로 연락드리겠습니다.' }}
        onSubmit={(values) => console.log(values)}
      />
    </section>
  )
}

속성

이름형식기본값설명
slots필수string[]—시간대
slotsByWeekdayPartial<Record<number, string[]>>—요일별 시간대(0 = 일요일 … 6 = 토요일). 토요일만 다를 때 등
closedWeekdaysnumber[][0, 6]막을 요일
holidaysstring[]—막을 날짜 'YYYY-MM-DD'(공휴일·휴원일)
daysnumber14보여 줄 날 수
includeTodaybooleanfalse오늘도 고를 수 있게(기본은 내일부터)
kindsstring[]—상담 종류. 주면 맨 위에 고르는 칸이 생긴다
memo{ label: string; placeholder?: string }—남기실 말씀 칸
labelsPartial<Record<'date' | 'slot' | 'name' | 'phone' | 'kind', string>>—항목 이름 바꾸기
agreestring—개인정보 수집·이용 동의 문구
submitLabelstring'예약 신청'보내기 버튼
done{ title: string; description?: string }—접수 뒤 문구
errorsPartial<Record<'date' | 'slot' | 'name' | 'phone' | 'agree', string>>—오류 문구 바꾸기
nowDate | string—현재 시각 고정(미리보기·시험용)
onSubmit(values: ReserveValues) => void | Promise<void>—values 는 date('YYYY-MM-DD')·slot·name·phone·kind·memo

원본 코드

설치 명령 없이 그대로 복사해 넣어도 됩니다. React 외의 패키지는 쓰지 않습니다.

components/bpublish/reserve-form.tsx
'use client'

/**
 * bpublish UI — 예약 양식. https://www.bpublish.com/designs/components/reserve-form
 * 상담·방문 예약. 앞으로 14일을 날짜 상자로 늘어놓고(휴무 요일·휴일은 막음) 시간대를 고른 뒤 이름·연락처·동의를 받는다.
 * 날짜는 화면이 뜬 뒤 현재 시각으로 계산한다(서버와 어긋나지 않게). now 로 고정할 수 있다.
 */
import { useEffect, useId, useState, type FormEvent } from 'react'

export type ReserveValues = {
  /** 'YYYY-MM-DD' */
  date: string
  slot: string
  name: string
  phone: string
  kind?: string
  memo?: string
}

type ErrorKey = 'date' | 'slot' | 'name' | 'phone' | 'agree'

export type ReserveFormProps = {
  /** 시간대. 요일마다 다르면 slotsByWeekday 로 덮는다 */
  slots: string[]
  /** 요일별 시간대(0 = 일요일 … 6 = 토요일) */
  slotsByWeekday?: Partial<Record<number, string[]>>
  /** 막을 요일. 기본은 토·일 */
  closedWeekdays?: number[]
  /** 막을 날짜 'YYYY-MM-DD' (공휴일·휴원일) */
  holidays?: string[]
  /** 보여 줄 날 수 */
  days?: number
  /** 오늘도 고를 수 있게 한다. 기본은 내일부터 */
  includeToday?: boolean
  /** 상담 종류(선택). 주면 맨 위에 고르는 칸이 생긴다 */
  kinds?: string[]
  /** 남기실 말씀 칸(선택) */
  memo?: { label: string; placeholder?: string }
  /** 항목 이름 바꾸기 */
  labels?: Partial<Record<'date' | 'slot' | 'name' | 'phone' | 'kind', string>>
  /** 동의 문구 */
  agree?: string
  submitLabel?: string
  done?: { title: string; description?: string }
  errors?: Partial<Record<ErrorKey, string>>
  /** 현재 시각을 고정한다(미리보기·시험용) */
  now?: Date | string
  onSubmit?: (values: ReserveValues) => void | Promise<void>
  className?: string
}

const WEEK = ['일', '월', '화', '수', '목', '금', '토']

const ERR: Record<ErrorKey, string> = {
  date: '날짜를 골라 주세요.',
  slot: '시간대를 골라 주세요.',
  name: '이름을 입력해 주세요.',
  phone: '연락처를 정확히 입력해 주세요.',
  agree: '개인정보 수집·이용에 동의해 주세요.',
}

const ymd = (d: Date) => `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`

const input =
  'mt-2 block h-14 w-full rounded-md border-2 border-input bg-background px-4 text-base text-foreground outline-none transition-colors placeholder:text-muted-foreground focus:border-ring aria-[invalid=true]:border-destructive'

const pill =
  'flex h-12 items-center justify-center rounded-md border-2 border-input px-3 text-[15px] font-semibold text-muted-foreground transition-colors peer-checked:border-primary peer-checked:bg-primary peer-checked:text-primary-foreground peer-focus-visible:outline-2 peer-focus-visible:outline-offset-2 peer-focus-visible:outline-ring peer-disabled:cursor-not-allowed peer-disabled:opacity-40'

export function ReserveForm({
  slots,
  slotsByWeekday = {},
  closedWeekdays = [0, 6],
  holidays = [],
  days = 14,
  includeToday = false,
  kinds,
  memo,
  labels = {},
  agree = '예약 확인을 위한 개인정보(이름, 연락처) 수집·이용에 동의합니다. 예약 후 6개월간 보관합니다.',
  submitLabel = '예약 신청',
  done = { title: '접수 완료', description: '예약 신청이 접수되었습니다. 남겨 주신 번호로 연락드려 시간을 확정합니다.' },
  errors: errorText = {},
  now,
  onSubmit,
  className = '',
}: ReserveFormProps) {
  const L = { date: '날짜', slot: '시간대', name: '이름', phone: '연락처', kind: '상담 종류', ...labels }
  const E = { ...ERR, ...errorText }
  const id = useId()
  const [list, setList] = useState<Date[] | null>(null)
  const [date, setDate] = useState('')
  const [slot, setSlot] = useState('')
  const [kind, setKind] = useState(kinds?.[0] ?? '')
  const [err, setErr] = useState<Partial<Record<ErrorKey, string>>>({})
  const [state, setState] = useState<'idle' | 'sending' | 'done'>('idle')
  const [sent, setSent] = useState<ReserveValues | null>(null)

  const nowKey = now ? new Date(now).getTime() : 0
  useEffect(() => {
    const base = now ? new Date(now) : new Date()
    base.setHours(0, 0, 0, 0)
    const out: Date[] = []
    for (let i = includeToday ? 0 : 1; out.length < days; i++) {
      const d = new Date(base)
      d.setDate(base.getDate() + i)
      out.push(d)
    }
    setList(out)
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [nowKey, days, includeToday])

  const closed = (d: Date) => closedWeekdays.includes(d.getDay()) || holidays.includes(ymd(d))
  const picked = list?.find((d) => ymd(d) === date)
  const daySlots = picked ? (slotsByWeekday[picked.getDay()] ?? slots) : slots
  const label = (d: Date) => `${d.getMonth() + 1}월 ${d.getDate()}일 (${WEEK[d.getDay()]})`

  async function submit(ev: FormEvent<HTMLFormElement>) {
    ev.preventDefault()
    const f = new FormData(ev.currentTarget)
    const s = (k: string) => String(f.get(k) ?? '').trim()
    const values: ReserveValues = { date, slot, name: s('name'), phone: s('phone'), kind: kinds ? kind : undefined, memo: memo ? s('memo') : undefined }
    const e: Partial<Record<ErrorKey, string>> = {}
    if (!date) e.date = E.date
    if (!slot) e.slot = E.slot
    if (!values.name) e.name = E.name
    if (values.phone.replace(/\D/g, '').length < 9) e.phone = E.phone
    if (!f.get('agree')) e.agree = E.agree
    setErr(e)
    const first = Object.keys(e)[0]
    if (first) {
      ev.currentTarget.querySelector<HTMLElement>(`[data-field="${first}"]`)?.focus()
      return
    }
    try {
      setState('sending')
      await onSubmit?.(values)
      setSent(values)
      setState('done')
    } catch {
      setState('idle')
    }
  }

  if (state === 'done' && sent) {
    const d = list?.find((x) => ymd(x) === sent.date)
    return (
      <div role="status" className={`flex min-h-[420px] flex-col justify-center rounded-lg border-2 border-primary p-8 md:p-12 ${className}`}>
        <p className="heading text-[44px] leading-none text-primary">{done.title}</p>
        {done.description ? <p className="mt-6 text-xl leading-relaxed font-semibold">{done.description}</p> : null}
        <p className="mt-3 text-[15px] text-muted-foreground tabular-nums">
          {d ? label(d) : sent.date} {sent.slot}
          {sent.kind ? ` · ${sent.kind}` : ''}
        </p>
      </div>
    )
  }

  const errOf = (k: ErrorKey) =>
    err[k] ? (
      <p id={`${id}-${k}-err`} className="mt-2 text-[13px] font-semibold text-destructive">
        {err[k]}
      </p>
    ) : null

  // 달이 바뀌는 자리에 달 이름을 붙인다
  let lastMonth = -1

  return (
    <form noValidate onSubmit={submit} className={`rounded-lg border border-border bg-card p-6 text-card-foreground md:p-10 ${className}`}>
      {kinds?.length ? (
        <fieldset className="mb-8">
          <legend className="mb-2 text-sm font-semibold">{L.kind}</legend>
          <div className="grid gap-1.5 sm:grid-cols-3">
            {kinds.map((k) => (
              <label key={k} className="cursor-pointer">
                <input type="radio" name="kind" value={k} checked={kind === k} onChange={() => setKind(k)} className="peer sr-only" />
                <span className={pill}>{k}</span>
              </label>
            ))}
          </div>
        </fieldset>
      ) : null}

      <fieldset aria-describedby={err.date ? `${id}-date-err` : undefined}>
        <legend className="mb-2 text-sm font-semibold">{L.date}</legend>
        <div className="grid grid-cols-7 gap-1 md:gap-1.5">
          {list
            ? list.map((d, i) => {
                const key = ymd(d)
                const off = closed(d)
                const month = d.getMonth()
                const showMonth = month !== lastMonth
                lastMonth = month
                return (
                  <label key={key} className={off ? 'cursor-not-allowed' : 'cursor-pointer'}>
                    <input
                      type="radio"
                      name="date"
                      value={key}
                      data-field={i === list.findIndex((x) => !closed(x)) ? 'date' : undefined}
                      checked={date === key}
                      disabled={off}
                      onChange={() => {
                        setDate(key)
                        if (slot && !(slotsByWeekday[d.getDay()] ?? slots).includes(slot)) setSlot('')
                      }}
                      aria-label={`${label(d)}${off ? ' 휴무' : ''}`}
                      className="peer sr-only"
                    />
                    <span
                      className={`relative flex aspect-square flex-col items-center justify-center rounded-md border-2 transition-colors peer-checked:border-primary peer-checked:bg-primary peer-checked:text-primary-foreground peer-focus-visible:outline-2 peer-focus-visible:outline-offset-2 peer-focus-visible:outline-ring md:aspect-auto md:h-20 ${
                        off ? 'border-transparent bg-muted text-muted-foreground line-through opacity-60' : 'border-input hover:border-foreground'
                      }`}
                    >
                      <span className="text-[11px] font-semibold md:text-[13px]">{WEEK[d.getDay()]}</span>
                      <span className="heading text-lg leading-none tabular-nums md:mt-1 md:text-[28px]">{d.getDate()}</span>
                      {showMonth ? (
                        <span className="absolute top-1 left-1.5 hidden text-[10px] font-semibold opacity-70 md:block">{month + 1}월</span>
                      ) : null}
                    </span>
                  </label>
                )
              })
            : Array.from({ length: days }, (_, i) => <span key={i} className="aspect-square rounded-md bg-muted md:aspect-auto md:h-20" />)}
        </div>
        {errOf('date')}
      </fieldset>

      <fieldset className="mt-6" aria-describedby={err.slot ? `${id}-slot-err` : undefined}>
        <legend className="mb-2 text-sm font-semibold">
          {L.slot}
          {picked ? <span className="ml-2 font-normal text-muted-foreground tabular-nums">{label(picked)}</span> : null}
        </legend>
        <div className="grid grid-cols-3 gap-1.5 sm:grid-cols-4 md:grid-cols-6">
          {daySlots.map((s, i) => (
            <label key={s} className="cursor-pointer">
              <input
                type="radio"
                name="slot"
                value={s}
                data-field={i === 0 ? 'slot' : undefined}
                checked={slot === s}
                onChange={() => setSlot(s)}
                className="peer sr-only"
              />
              <span className={`${pill} tabular-nums`}>{s}</span>
            </label>
          ))}
        </div>
        {errOf('slot')}
      </fieldset>

      <div className="mt-6 grid gap-5 sm:grid-cols-2">
        <div>
          <label htmlFor={`${id}-name`} className="text-sm font-semibold">
            {L.name}
          </label>
          <input
            id={`${id}-name`}
            name="name"
            data-field="name"
            autoComplete="name"
            aria-invalid={err.name ? true : undefined}
            aria-describedby={err.name ? `${id}-name-err` : undefined}
            className={input}
          />
          {errOf('name')}
        </div>
        <div>
          <label htmlFor={`${id}-phone`} className="text-sm font-semibold">
            {L.phone}
          </label>
          <input
            id={`${id}-phone`}
            name="phone"
            data-field="phone"
            type="tel"
            inputMode="tel"
            autoComplete="tel"
            placeholder="010-0000-0000"
            aria-invalid={err.phone ? true : undefined}
            aria-describedby={err.phone ? `${id}-phone-err` : undefined}
            className={`${input} tabular-nums`}
          />
          {errOf('phone')}
        </div>
      </div>

      {memo ? (
        <div className="mt-6">
          <label htmlFor={`${id}-memo`} className="text-sm font-semibold">
            {memo.label}
          </label>
          <textarea id={`${id}-memo`} name="memo" rows={3} placeholder={memo.placeholder} className={`${input} h-auto resize-none py-3 leading-relaxed`} />
        </div>
      ) : null}

      <label className="mt-5 flex cursor-pointer items-start gap-3 text-sm leading-relaxed text-muted-foreground">
        <input
          name="agree"
          data-field="agree"
          type="checkbox"
          aria-invalid={err.agree ? true : undefined}
          className="mt-0.5 size-5 shrink-0 accent-primary focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-ring"
        />
        <span>{agree}</span>
      </label>
      {errOf('agree')}

      <button
        type="submit"
        disabled={state === 'sending'}
        className="mt-6 flex h-16 w-full items-center justify-center rounded-lg bg-primary text-lg font-semibold text-primary-foreground transition-opacity hover:opacity-90 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-ring disabled:opacity-60"
      >
        {state === 'sending' ? '보내는 중…' : submitLabel}
      </button>
    </form>
  )
}