부품 데이터·관리 화면

데이터 표 data-table

주문·회원 목록 같은 관리 화면의 표. 열 정의로 정렬 가능한 열, 오른쪽 정렬 숫자 열, 배지 같은 칸 꾸밈을 정한다. 좁은 화면에서는 줄마다 카드로 접히거나 가로로 밀어 본다. 상태 칸용 TableBadge 를 같이 내보낸다.

  • 나온 곳 대시보드
  • 표
  • 테이블
  • 정렬
  • 주문 목록
  • 배지
  • 대시보드

설치

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

npx shadcn@latest add https://www.bpublish.com/r/data-table.json

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

AI에게 맡기기

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

bpublish UI의 데이터 표(data-table) 부품으로 만들어 줘. 설치: npx shadcn@latest add https://www.bpublish.com/r/data-table.json · 문서: https://www.bpublish.com/designs/components/data-table

사용 예시

app/page.tsx
'use client'

import { DataTable, TableBadge, type DataTableColumn, type TableBadgeTone } from '@/components/bpublish/data-table'

type Order = { id: string; customer: string; email: string; item: string; amount: number; status: keyof typeof STATUS; minutes: number }

const STATUS = {
  paid: { label: '결제 완료', tone: 'primary' },
  shipping: { label: '배송 중', tone: 'warning' },
  delivered: { label: '배송 완료', tone: 'success' },
  refund: { label: '환불 요청', tone: 'danger' },
} satisfies Record<string, { label: string; tone: TableBadgeTone }>

const orders: Order[] = [
  { id: 'A-20418', customer: '김서연', email: 'seoyeon@example.com', item: '리넨 오버셔츠 외 1건', amount: 128400, status: 'paid', minutes: 12 },
  { id: 'A-20417', customer: '이도윤', email: 'doyoon@example.com', item: '울 블렌드 머플러', amount: 59000, status: 'paid', minutes: 34 },
  { id: 'A-20416', customer: '박지우', email: 'jiwoo@example.com', item: '캔버스 토트백', amount: 42000, status: 'shipping', minutes: 60 },
  { id: 'A-20415', customer: '최하준', email: 'hajun@example.com', item: '코튼 니트 가디건 외 2건', amount: 214600, status: 'shipping', minutes: 120 },
  { id: 'A-20414', customer: '정유나', email: 'yuna@example.com', item: '세라믹 머그 세트', amount: 36000, status: 'refund', minutes: 180 },
  { id: 'A-20413', customer: '강민재', email: 'minjae@example.com', item: '와이드 치노 팬츠', amount: 69000, status: 'delivered', minutes: 300 },
]

const ago = (m: number) => (m < 60 ? `${m}분 전` : `${Math.round(m / 60)}시간 전`)

const columns: DataTableColumn<Order>[] = [
  { key: 'id', header: '주문', sortable: true, render: (o) => <span className="font-medium tabular-nums">#{o.id}</span> },
  {
    key: 'customer',
    header: '고객',
    card: 'title',
    render: (o) => (
      <div className="flex items-center gap-2.5 text-left">
        <span aria-hidden className="grid size-7 shrink-0 place-items-center rounded-full bg-accent text-xs font-semibold text-accent-foreground">
          {o.customer.slice(0, 1)}
        </span>
        <div className="min-w-0">
          <p className="truncate font-medium">{o.customer}</p>
          <p className="truncate text-xs font-normal text-muted-foreground">{o.email}</p>
        </div>
      </div>
    ),
  },
  { key: 'item', header: '상품', hideBelow: 'md', className: 'max-w-56 truncate text-muted-foreground' },
  { key: 'amount', header: '금액', numeric: true, sortable: true, card: 'aside', render: (o) => <span className="font-medium">{o.amount.toLocaleString('ko-KR')}원</span> },
  { key: 'status', header: '상태', card: 'aside', render: (o) => <TableBadge tone={STATUS[o.status].tone}>{STATUS[o.status].label}</TableBadge> },
  { key: 'minutes', header: '시간', numeric: true, sortable: true, hideBelow: 'sm', card: 'hide', render: (o) => <span className="text-muted-foreground">{ago(o.minutes)}</span> },
]

export default function Example() {
  return (
    <DataTable
      title="최근 주문"
      description="오늘 들어온 주문 6건"
      columns={columns}
      rows={orders}
      rowKey={(o) => o.id}
      action={
        <a href="#orders" className="inline-flex h-8 items-center rounded-lg border border-border bg-card px-3 text-[13px] font-medium hover:bg-accent">
          전체 보기
        </a>
      }
    />
  )
}

속성

이름형식기본값설명
columns필수DataTableColumn<T>[]—열 정의: { key, header, numeric?, sortable?, sortValue?, render?, hideBelow?: 'sm'|'md'|'lg', card?: 'title'|'aside'|'hide', className? }
rows필수T[]—줄 데이터
rowKey필수(row: T) => string—줄마다 다른 값
titlestring—표 위 제목
descriptionstring—제목 아래 한 줄
actionReactNode—머리 오른쪽(전체 보기 등)
mobile'cards' | 'scroll''cards'640px 아래에서 줄마다 카드로 접기, 또는 가로 스크롤
defaultSort{ key: string; dir: 'asc' | 'desc' }—처음 정렬
emptystring'내용이 없습니다'줄이 없을 때 글

원본 코드

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

components/bpublish/data-table.tsx
'use client'

/**
 * bpublish UI — 데이터 표. https://www.bpublish.com/designs/components/data-table
 * 주문·회원 목록 같은 관리 화면의 표. 열 정의를 props 로 받아 머리를 눌러 정렬하고,
 * 숫자 열은 오른쪽에 맞춘다. 좁은 화면에서는 줄마다 카드로 접히거나(cards) 가로로 밀어 본다(scroll).
 * 상태 칸에는 같이 내보내는 TableBadge 를 render 에서 쓴다.
 */
import * as React from 'react'

export type DataTableColumn<T> = {
  /** 열 이름표. render 가 없으면 row[key] 를 그대로 보인다 */
  key: string
  header: string
  /** 숫자 열: 오른쪽 정렬, 고정폭 숫자 */
  numeric?: boolean
  sortable?: boolean
  /** 정렬에 쓸 값. 없으면 row[key] */
  sortValue?: (row: T) => string | number
  /** 칸 내용. 배지·아바타처럼 꾸밀 때 */
  render?: (row: T) => React.ReactNode
  /** 이 폭보다 좁은 화면의 표에서 열을 숨긴다 */
  hideBelow?: 'sm' | 'md' | 'lg'
  /** 카드로 접혔을 때 자리. title: 카드 머리 왼쪽 / aside: 머리 오른쪽 / hide: 숨김. 나머지는 이름·값 줄 */
  card?: 'title' | 'aside' | 'hide'
  /** 칸에 더할 클래스(폭 제한 등) */
  className?: string
}

export type DataTableProps<T> = {
  columns: DataTableColumn<T>[]
  rows: T[]
  /** 줄마다 다른 값(주문 번호 등) */
  rowKey: (row: T) => string
  /** 표 위 머리 */
  title?: string
  description?: string
  /** 머리 오른쪽(전체 보기 버튼 등) */
  action?: React.ReactNode
  /** 좁은 화면(640px 아래) 처리. cards: 줄마다 카드 / scroll: 가로 스크롤 */
  mobile?: 'cards' | 'scroll'
  /** 처음 정렬 */
  defaultSort?: { key: string; dir: 'asc' | 'desc' }
  /** 줄이 없을 때 글 */
  empty?: string
  className?: string
}

const cx = (...v: Array<string | false | null | undefined>) => v.filter(Boolean).join(' ')
const HIDE = { sm: 'hidden sm:table-cell', md: 'hidden md:table-cell', lg: 'hidden lg:table-cell' } as const
const ring = 'focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-ring'

function raw<T>(row: T, key: string): unknown {
  return (row as Record<string, unknown>)[key]
}

export function DataTable<T>({
  columns,
  rows,
  rowKey,
  title,
  description,
  action,
  mobile = 'cards',
  defaultSort,
  empty = '내용이 없습니다',
  className,
}: DataTableProps<T>) {
  const [sort, setSort] = React.useState(defaultSort ?? null)

  const sorted = React.useMemo(() => {
    if (!sort) return rows
    const col = columns.find((c) => c.key === sort.key)
    if (!col) return rows
    const val = (r: T) => (col.sortValue ? col.sortValue(r) : (raw(r, col.key) as string | number))
    const out = [...rows].sort((a, b) => {
      const x = val(a)
      const y = val(b)
      return typeof x === 'number' && typeof y === 'number' ? x - y : String(x ?? '').localeCompare(String(y ?? ''), 'ko')
    })
    return sort.dir === 'desc' ? out.reverse() : out
  }, [rows, columns, sort])

  const toggle = (c: DataTableColumn<T>) =>
    setSort((s) => (s?.key === c.key ? { key: c.key, dir: s.dir === 'asc' ? 'desc' : 'asc' } : { key: c.key, dir: c.numeric ? 'desc' : 'asc' }))

  const cell = (c: DataTableColumn<T>, r: T) => (c.render ? c.render(r) : String(raw(r, c.key) ?? ''))
  const edge = (i: number) => cx(i === 0 ? 'pl-5' : 'pl-3', i === columns.length - 1 ? 'pr-5' : 'pr-3')

  const titleCols = columns.filter((c) => c.card === 'title')
  const heads = titleCols.length ? titleCols : columns.slice(0, 1)
  const asides = columns.filter((c) => c.card === 'aside')
  const rest = columns.filter((c) => !heads.includes(c) && !asides.includes(c) && c.card !== 'hide')

  return (
    <section className={cx('flex flex-col overflow-hidden rounded-lg border border-border bg-card text-card-foreground', className)}>
      {title ? (
        <header className="flex items-start justify-between gap-4 px-5 pt-5">
          <div className="min-w-0">
            <h2 className="text-sm font-semibold tracking-tight">{title}</h2>
            {description ? <p className="mt-1 text-[13px] leading-5 text-muted-foreground">{description}</p> : null}
          </div>
          {action ? <div className="flex shrink-0 items-center gap-2">{action}</div> : null}
        </header>
      ) : null}

      <div className={cx(title && 'mt-4', 'overflow-x-auto', mobile === 'cards' && 'hidden sm:block')}>
        <table className={cx('w-full text-left text-[13px]', mobile === 'scroll' && 'min-w-[560px]')}>
          <thead>
            <tr className={cx('border-b border-border bg-muted/50 text-xs text-muted-foreground', title && 'border-t')}>
              {columns.map((c, i) => {
                const dir = sort?.key === c.key ? sort.dir : null
                return (
                  <th
                    key={c.key}
                    scope="col"
                    aria-sort={dir ? (dir === 'asc' ? 'ascending' : 'descending') : undefined}
                    className={cx('py-2.5 font-medium whitespace-nowrap', edge(i), c.numeric && 'text-right', c.hideBelow && HIDE[c.hideBelow])}
                  >
                    {c.sortable ? (
                      <button
                        type="button"
                        onClick={() => toggle(c)}
                        className={cx('-mx-1 inline-flex items-center gap-1 rounded-sm px-1 transition-colors hover:text-foreground', dir && 'text-foreground', ring)}
                      >
                        {c.header}
                        <SortIcon dir={dir} />
                      </button>
                    ) : (
                      c.header
                    )}
                  </th>
                )
              })}
            </tr>
          </thead>
          <tbody className="divide-y divide-border">
            {sorted.map((r) => (
              <tr key={rowKey(r)} className="transition-colors hover:bg-muted/40">
                {columns.map((c, i) => (
                  <td
                    key={c.key}
                    className={cx('py-3', edge(i), c.numeric && 'text-right whitespace-nowrap tabular-nums', c.hideBelow && HIDE[c.hideBelow], c.className)}
                  >
                    {cell(c, r)}
                  </td>
                ))}
              </tr>
            ))}
          </tbody>
        </table>
      </div>

      {mobile === 'cards' ? (
        <ul className={cx('divide-y divide-border sm:hidden', title && 'mt-4 border-t border-border')}>
          {sorted.map((r) => (
            <li key={rowKey(r)} className="px-5 py-4 text-[13px]">
              <div className="flex items-start justify-between gap-3">
                <div className="min-w-0 space-y-0.5 font-medium">
                  {heads.map((c) => (
                    <div key={c.key} className={cx(c.numeric && 'tabular-nums')}>
                      {cell(c, r)}
                    </div>
                  ))}
                </div>
                {asides.length ? (
                  <div className="flex shrink-0 flex-col items-end gap-1">
                    {asides.map((c) => (
                      <div key={c.key} className={cx(c.numeric && 'font-medium tabular-nums')}>
                        {cell(c, r)}
                      </div>
                    ))}
                  </div>
                ) : null}
              </div>
              {rest.length ? (
                <dl className="mt-3 space-y-1.5">
                  {rest.map((c) => (
                    <div key={c.key} className="flex items-center justify-between gap-4">
                      <dt className="shrink-0 text-xs text-muted-foreground">{c.header}</dt>
                      <dd className={cx('flex min-w-0 justify-end text-right', c.numeric && 'tabular-nums')}>{cell(c, r)}</dd>
                    </div>
                  ))}
                </dl>
              ) : null}
            </li>
          ))}
        </ul>
      ) : null}

      {rows.length === 0 ? <p className="px-5 py-10 text-center text-[13px] text-muted-foreground">{empty}</p> : null}
    </section>
  )
}

function SortIcon({ dir }: { dir: 'asc' | 'desc' | null }) {
  return (
    <svg aria-hidden viewBox="0 0 24 24" className="size-3.5" fill="none" stroke="currentColor" strokeWidth={1.5} strokeLinecap="round" strokeLinejoin="round">
      <path d="m8 9.5 4-4 4 4" opacity={dir === 'desc' ? 0.3 : 1} />
      <path d="m8 14.5 4 4 4-4" opacity={dir === 'asc' ? 0.3 : 1} />
    </svg>
  )
}

/* ── 상태 배지 ─────────────────────────────────────────────────── */

export type TableBadgeTone = 'neutral' | 'primary' | 'success' | 'warning' | 'danger'

/* 성공·주의 색이 없는 테마에서는 강조색·보조 글 색으로 대신한다 */
const TONE: Record<TableBadgeTone, string> = {
  neutral: 'bg-muted text-muted-foreground',
  primary: 'bg-primary/10 text-primary',
  success: 'bg-[color-mix(in_oklab,var(--success,var(--foreground))_12%,transparent)] text-[color-mix(in_oklab,var(--success,var(--foreground))_85%,var(--foreground))]',
  warning: 'bg-[color-mix(in_oklab,var(--warning,var(--muted-foreground))_16%,transparent)] text-[color-mix(in_oklab,var(--warning,var(--muted-foreground))_65%,var(--foreground))]',
  danger: 'bg-destructive/10 text-destructive',
}

export function TableBadge({ tone = 'neutral', children }: { tone?: TableBadgeTone; children: React.ReactNode }) {
  return (
    <span className={cx('inline-flex h-6 items-center gap-1.5 rounded-full px-2.5 text-xs font-medium whitespace-nowrap', TONE[tone])}>
      <span aria-hidden className="size-1.5 rounded-full bg-current" />
      {children}
    </span>
  )
}