부품 입력·예약

문의 양식 inquiry-form

이름·회사·연락처·이메일·문의 구분·내용·첨부와 개인정보 수집·이용 동의(내용 펼쳐 보기). 보내기 전에 필수 항목과 형식을 확인해 칸 아래에 오류를 적고, 통과하면 onSubmit(values) 를 부른 뒤 감사 문구로 바뀐다.

  • 나온 곳 한결정밀
  • 문의
  • 견적
  • 양식
  • 개인정보 동의
  • 첨부

설치

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

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

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

AI에게 맡기기

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

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

사용 예시

app/page.tsx
'use client'

import { InquiryForm } from '@/components/bpublish/inquiry-form'

export default function Example() {
  return (
    <section className="shell py-16 md:py-24">
      <h2 className="heading text-3xl md:text-5xl">견적 문의</h2>
      <p className="mt-4 max-w-xl text-[15px] leading-7 text-muted-foreground">도면과 수량, 희망 납기를 알려 주시면 담당 엔지니어가 직접 회신합니다.</p>
      <InquiryForm
        className="mt-10"
        labels={{ name: '담당자', type: '문의 유형', attachment: '도면 첨부' }}
        types={['신규 견적', '시제품 제작', '양산 전환', '기존 주문 문의', '기타']}
        messagePlaceholder="소재, 표면 처리, 공차 등 요구 사항을 적어 주세요."
        attachmentNote="STEP, IGES, DWG, DXF, PDF · 파일당 최대 30MB"
        attachmentAccept=".step,.stp,.iges,.igs,.dwg,.dxf,.pdf"
        maxFileMB={30}
        privacy={{
          rows: [
            { label: '수집 항목', value: '담당자, 회사명, 연락처, 이메일' },
            { label: '이용 목적', value: '견적 회신과 문의 처리' },
            { label: '보유 기간', value: '문의 처리 후 1년' },
          ],
        }}
        submitLabel="견적 문의 보내기"
        done={{ title: '문의가 접수되었습니다.', description: '담당 엔지니어가 영업일 기준 하루 안에 연락드립니다.' }}
        onSubmit={(values) => console.log(values)}
      />
    </section>
  )
}

속성

이름형식기본값설명
onSubmit(values: InquiryValues) => void | Promise<void>—확인을 통과하면 부른다. values 는 name·company·phone·email·type·message·files. Promise 면 끝날 때까지 「보내는 중」, 실패하면 전송 오류 문구
fields{ company?: boolean; email?: boolean; type?: boolean; attachment?: boolean }모두 true받을 항목을 켜고 끈다. 이름·연락처·내용·동의는 늘 받는다. 이메일은 켜면 필수, 회사명·첨부는 선택
typesstring[]['일반 문의', '견적 문의', '제휴 제안', '기타']문의 구분 목록
labelsPartial<Record<'name' | 'company' | 'phone' | 'email' | 'type' | 'message' | 'attachment', string>>—항목 이름 바꾸기(담당자, 문의 유형 등)
messagePlaceholderstring—내용 칸 안내 글
attachmentNotestring—첨부 칸 아래 안내(형식·크기)
attachmentAcceptstring—첨부 허용 형식(input accept)
maxFileMBnumber—파일 하나의 최대 크기. 넘으면 오류
privacy{ label?: string; rows: { label: string; value: string }[]; note?: string }—동의 문구와 「내용 보기」 안의 수집 항목·이용 목적·보유 기간
submitLabelstring'문의 보내기'보내기 버튼
done{ title: string; description?: string }—보낸 뒤 감사 문구
errorsPartial<Record<ErrorKey, string>>—오류 문구 바꾸기(name, phone, phoneFormat, email, emailFormat, message, fileSize, agree, summary, send)

원본 코드

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

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

/**
 * bpublish UI — 문의 양식. https://www.bpublish.com/designs/components/inquiry-form
 * 이름·회사·연락처·이메일·문의 구분·내용·첨부와 개인정보 수집·이용 동의. 보내기 전에 필수 항목을 확인하고,
 * 다 맞으면 onSubmit(values) 를 부른 뒤 감사 문구로 바뀐다. 실제 전송(메일 API, 폼 서비스)은 onSubmit 안에서 한다.
 */
import { useId, useRef, useState, type FormEvent, type ReactNode } from 'react'

export type InquiryValues = {
  name: string
  company: string
  phone: string
  email: string
  type: string
  message: string
  files: File[]
}

type FieldKey = 'name' | 'company' | 'phone' | 'email' | 'type' | 'message' | 'attachment'
type ErrorKey = 'name' | 'phone' | 'phoneFormat' | 'email' | 'emailFormat' | 'message' | 'fileSize' | 'agree' | 'summary' | 'send'

export type InquiryFormProps = {
  /** 받을 항목. 이름·연락처·내용은 늘 받는다. 기본은 모두 켬 */
  fields?: { company?: boolean; email?: boolean; type?: boolean; attachment?: boolean }
  /** 문의 구분 목록(select). 첫 번째가 기본값 */
  types?: string[]
  /** 항목 이름 바꾸기 */
  labels?: Partial<Record<FieldKey, string>>
  messagePlaceholder?: string
  /** 첨부 칸 아래 안내(받는 형식·크기) */
  attachmentNote?: string
  /** 첨부 허용 형식. input accept 그대로 */
  attachmentAccept?: string
  /** 파일 하나의 최대 크기(MB) */
  maxFileMB?: number
  /** 개인정보 수집·이용 동의. 표는 「내용 보기」를 누르면 펼쳐진다 */
  privacy?: { label?: string; rows: { label: string; value: string }[]; note?: string }
  submitLabel?: string
  /** 보낸 뒤 보이는 감사 문구 */
  done?: { title: string; description?: string }
  /** 오류 문구 바꾸기 */
  errors?: Partial<Record<ErrorKey, string>>
  /** 확인을 통과하면 부른다. Promise 를 돌려주면 끝날 때까지 「보내는 중」, 실패하면 오류 문구 */
  onSubmit?: (values: InquiryValues) => void | Promise<void>
  className?: string
}

const ERR: Record<ErrorKey, string> = {
  name: '이름을 입력해 주세요.',
  phone: '연락처를 입력해 주세요.',
  phoneFormat: '연락처를 숫자로 정확히 입력해 주세요.',
  email: '이메일을 입력해 주세요.',
  emailFormat: '이메일 주소 형식을 확인해 주세요.',
  message: '문의 내용을 입력해 주세요.',
  fileSize: '첨부 파일이 너무 큽니다.',
  agree: '개인정보 수집·이용에 동의해 주세요.',
  summary: '표시한 항목을 확인해 주세요.',
  send: '보내지 못했습니다. 잠시 뒤 다시 보내 주시거나 전화로 문의해 주세요.',
}

const LABEL: Record<FieldKey, string> = {
  name: '이름',
  company: '회사명',
  phone: '연락처',
  email: '이메일',
  type: '문의 구분',
  message: '문의 내용',
  attachment: '파일 첨부',
}

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

export function InquiryForm({
  fields = {},
  types = ['일반 문의', '견적 문의', '제휴 제안', '기타'],
  labels = {},
  messagePlaceholder,
  attachmentNote,
  attachmentAccept,
  maxFileMB,
  privacy = {
    rows: [
      { label: '수집 항목', value: '이름, 연락처, 이메일, 회사명' },
      { label: '이용 목적', value: '문의 확인과 답변' },
      { label: '보유 기간', value: '문의 처리 후 1년' },
    ],
  },
  submitLabel = '문의 보내기',
  done = { title: '문의가 접수되었습니다.', description: '확인하는 대로 남겨 주신 연락처로 답변드리겠습니다.' },
  errors: errorText = {},
  onSubmit,
  className = '',
}: InquiryFormProps) {
  const on = { company: true, email: true, type: true, attachment: true, ...fields }
  const L = { ...LABEL, ...labels }
  const E = { ...ERR, ...errorText }
  const id = useId()
  const formRef = useRef<HTMLFormElement>(null)
  const [state, setState] = useState<'idle' | 'sending' | 'done'>('idle')
  const [tried, setTried] = useState(false)
  const [err, setErr] = useState<Partial<Record<string, string>>>({})
  const [sendError, setSendError] = useState(false)

  function read(form: HTMLFormElement) {
    const d = new FormData(form)
    const s = (k: string) => String(d.get(k) ?? '').trim()
    const files = on.attachment ? (d.getAll('files') as File[]).filter((f) => f.size > 0) : []
    const values: InquiryValues = {
      name: s('name'),
      company: on.company ? s('company') : '',
      phone: s('phone'),
      email: on.email ? s('email') : '',
      type: on.type ? s('type') : '',
      message: s('message'),
      files,
    }
    const e: Partial<Record<string, string>> = {}
    if (!values.name) e.name = E.name
    if (!values.phone) e.phone = E.phone
    else if (!/^[0-9+\-\s()]+$/.test(values.phone) || values.phone.replace(/\D/g, '').length < 9) e.phone = E.phoneFormat
    if (on.email) {
      if (!values.email) e.email = E.email
      else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(values.email)) e.email = E.emailFormat
    }
    if (!values.message) e.message = E.message
    if (maxFileMB && files.some((f) => f.size > maxFileMB * 1024 * 1024)) e.files = E.fileSize
    if (!d.get('agree')) e.agree = E.agree
    return { values, e }
  }

  async function submit(ev: FormEvent<HTMLFormElement>) {
    ev.preventDefault()
    const form = ev.currentTarget
    const { values, e } = read(form)
    setTried(true)
    setErr(e)
    setSendError(false)
    const first = Object.keys(e)[0]
    if (first) {
      form.querySelector<HTMLElement>(`[name="${first}"]`)?.focus()
      return
    }
    try {
      setState('sending')
      await onSubmit?.(values)
      setState('done')
    } catch {
      setState('idle')
      setSendError(true)
    }
  }

  if (state === 'done') {
    return (
      <div role="status" className={`rounded-lg border-2 border-primary p-8 md:p-10 ${className}`}>
        <p className="heading text-xl md:text-2xl">{done.title}</p>
        {done.description ? <p className="mt-2 text-[15px] leading-7 text-muted-foreground">{done.description}</p> : null}
      </div>
    )
  }

  const fieldProps = (k: string) => ({
    id: `${id}-${k}`,
    name: k,
    'aria-invalid': err[k] ? true : undefined,
    'aria-describedby': err[k] ? `${id}-${k}-err` : undefined,
  })
  const errOf = (k: string) =>
    err[k] ? (
      <p id={`${id}-${k}-err`} className="mt-1.5 text-[13px] font-medium text-destructive">
        {err[k]}
      </p>
    ) : null
  const labelOf = (k: string, text: string, required = false) => (
    <label htmlFor={`${id}-${k}`} className="text-sm font-semibold">
      {text}
      {required ? (
        <span className="ml-0.5 text-primary" aria-hidden>
          *
        </span>
      ) : (
        <span className="ml-1 font-normal text-muted-foreground">(선택)</span>
      )}
    </label>
  )

  const half: ReactNode[] = [
    <div key="name">
      {labelOf('name', L.name, true)}
      <input {...fieldProps('name')} autoComplete="name" required className={input} />
      {errOf('name')}
    </div>,
    on.company ? (
      <div key="company">
        {labelOf('company', L.company)}
        <input {...fieldProps('company')} autoComplete="organization" className={input} />
      </div>
    ) : null,
    <div key="phone">
      {labelOf('phone', L.phone, true)}
      <input {...fieldProps('phone')} type="tel" inputMode="tel" autoComplete="tel" placeholder="010-0000-0000" required className={`${input} tabular-nums`} />
      {errOf('phone')}
    </div>,
    on.email ? (
      <div key="email">
        {labelOf('email', L.email, true)}
        <input {...fieldProps('email')} type="email" autoComplete="email" required className={input} />
        {errOf('email')}
      </div>
    ) : null,
    on.type ? (
      <div key="type">
        <label htmlFor={`${id}-type`} className="text-sm font-semibold">
          {L.type}
        </label>
        <div className="relative">
          <select {...fieldProps('type')} defaultValue={types[0]} className={`${input} appearance-none pr-10`}>
            {types.map((t) => (
              <option key={t}>{t}</option>
            ))}
          </select>
          <svg aria-hidden viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth={1.5} className="pointer-events-none absolute top-1/2 right-3 size-5 -translate-y-1/2 text-muted-foreground">
            <path d="m6 9 6 6 6-6" strokeLinecap="round" strokeLinejoin="round" />
          </svg>
        </div>
      </div>
    ) : null,
  ].filter(Boolean)

  return (
    <form
      ref={formRef}
      noValidate
      onSubmit={submit}
      onChange={() => {
        if (tried && formRef.current) setErr(read(formRef.current).e)
      }}
      className={`grid grid-cols-1 gap-x-6 gap-y-6 border-t-2 border-foreground pt-8 sm:grid-cols-2 ${className}`}
    >
      {half.map((node, i) => (
        <div key={i} className={half.length % 2 === 1 && i === half.length - 1 ? 'sm:col-span-2' : ''}>
          {node}
        </div>
      ))}

      <div className="sm:col-span-2">
        {labelOf('message', L.message, true)}
        <textarea {...fieldProps('message')} rows={6} required placeholder={messagePlaceholder} className={`${input} h-auto py-3 leading-7`} />
        {errOf('message')}
      </div>

      {on.attachment ? (
        <div className="sm:col-span-2">
          {labelOf('files', L.attachment)}
          <input
            {...fieldProps('files')}
            type="file"
            multiple
            accept={attachmentAccept}
            className="mt-2 block w-full rounded-md border border-dashed border-input bg-muted px-4 py-5 text-sm text-muted-foreground file:mr-4 file:cursor-pointer file:rounded-md file:border-0 file:bg-foreground file:px-4 file:py-2 file:text-sm file:font-semibold file:text-background focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-ring"
          />
          {attachmentNote ? <p className="mt-1.5 text-xs text-muted-foreground">{attachmentNote}</p> : null}
          {errOf('files')}
        </div>
      ) : null}

      <div className="sm:col-span-2">
        <div className="flex items-start gap-3 text-sm">
          <input
            {...fieldProps('agree')}
            type="checkbox"
            required
            className="mt-0.5 size-5 shrink-0 accent-primary focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-ring"
          />
          <label htmlFor={`${id}-agree`} className="leading-6">
            {privacy.label ?? '개인정보 수집·이용에 동의합니다.'}
            <span className="ml-0.5 text-primary" aria-hidden>
              *
            </span>
          </label>
        </div>
        <details className="group mt-2 ml-8 text-[13px] [&_summary::-webkit-details-marker]:hidden">
          <summary className="inline-flex cursor-pointer list-none items-center gap-1 text-muted-foreground underline-offset-4 hover:underline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-ring">
            내용 보기
            <svg aria-hidden viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth={1.5} className="size-4 transition-transform group-open:rotate-180">
              <path d="m6 9 6 6 6-6" strokeLinecap="round" strokeLinejoin="round" />
            </svg>
          </summary>
          <div className="mt-3 rounded-md border border-border bg-muted p-4 leading-6 text-muted-foreground">
            <dl className="grid grid-cols-[5.5rem_1fr] gap-y-1">
              {privacy.rows.map((r) => (
                <div key={r.label} className="contents">
                  <dt className="font-medium text-foreground">{r.label}</dt>
                  <dd>{r.value}</dd>
                </div>
              ))}
            </dl>
            <p className="mt-3">{privacy.note ?? '동의를 거부하실 수 있으나, 거부하시면 문의를 접수할 수 없습니다.'}</p>
          </div>
        </details>
        {errOf('agree')}
      </div>

      <div className="flex flex-col gap-4 sm:col-span-2 sm:flex-row sm:items-center">
        <button
          type="submit"
          disabled={state === 'sending'}
          className="h-14 w-full rounded-lg bg-primary px-12 text-base 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 sm:w-auto"
        >
          {state === 'sending' ? '보내는 중…' : submitLabel}
        </button>
        {sendError ? (
          <p role="alert" className="text-sm font-medium text-destructive">
            {E.send}
          </p>
        ) : tried && Object.keys(err).length ? (
          <p role="alert" className="text-sm font-medium text-destructive">
            {E.summary}
          </p>
        ) : null}
      </div>
    </form>
  )
}