@fw-components/data-grid

中文文档
2.7.1发布于 2026/11/13ISCTypeScriptES Module构建来源已验证近 30 天下载 3674

A high-performance, editable data grid for React with built-in virtualization, sorting, filtering, and bulk editing.

原始使用文档
文档目录22 节
  1. Features
  2. Installation
  3. Peer Dependencies
  4. Styling
  5. Quick Start
  6. Editing
  7. Cell Editing
  8. Custom Edit Components
  9. Bulk Editing
  10. Row Selection
  11. Virtualization
  12. Column Formatting
  13. Custom Format Function
  14. API Reference
  15. <DataGrid> Props
  16. DataGridFeatures
  17. Column Meta
  18. Hooks
  19. Keyboard Shortcuts
  20. Showcase / Demo
  21. Browser Support
  22. Contributing

@fw-components/data-grid

A high-performance, editable data grid for React with built-in virtualization, sorting, filtering, column management, and bulk editing. Built on TanStack Table and TanStack Virtual.

Features

  • 🚀 Virtualized rendering — handles thousands of rows with smooth scrolling
  • ✏️ Cell editing — click-to-edit with text, number, date, select, and boolean editors
  • 📋 Bulk editing — select multiple rows and edit a field across all of them
  • 🔍 Global search — instant text filtering with tree-aware matching
  • ↕️ Sorting — single and multi-column sorting
  • 📌 Column pinning — pin columns to left or right
  • ↔️ Column resizing — drag to resize columns
  • 🌲 Row expansion — hierarchical/nested data with custom sub-content
  • ☑️ Row selection — checkbox selection with select-all
  • 🎨 Customizable — custom cell renderers, edit components, and styling
  • ♿ Accessible — proper ARIA roles, keyboard navigation
  • 📦 Zero runtime deps — only React and TanStack as peer dependencies

Installation

npm install @fw-components/data-grid @tanstack/react-table @tanstack/react-virtual

Peer Dependencies

{
  "react": ">=18.0.0",
  "react-dom": ">=18.0.0",
  "@tanstack/react-table": "^8.0.0",
  "@tanstack/react-virtual": "^3.0.0"
}

Styling

The package ships a pre-built, ready-to-use stylesheet, you don't need Tailwind in your own app to use it. All utility classes emitted by these components are namespaced with the fwgrid: prefix (e.g. fwgrid:flex, fwgrid:bg-blue-600), so they can't collide with your app's own Tailwind (or other) classes, and only the classes actually used by the grid are included in the build. There are two ways to bring the stylesheet into your app.

Option 1: CSS file import (regular DOM)

For a normal (non-shadow-root) app, import the CSS file once in your app entry point and let your bundler emit it as a <link>/inlined <style> the usual way:

import "@fw-components/data-grid/styles.css";

Option 2: CSS-as-string import (Shadow DOM / dynamic injection)

If your app (or the part of it rendering the grid) lives inside a shadow root, a plain <link>/global <style> tag won't reach it. For that case (or any other scenario where you need the CSS as a JS string rather than a file path, e.g. your own build pipeline can't process the pre-compiled CSS file as-is), the same compiled output is also published as a JS module:

import { styles } from "@fw-components/data-grid/styles";

const sheet = new CSSStyleSheet();
sheet.replaceSync(styles);
shadowRoot.adoptedStyleSheets = [sheet];

Or, without constructable stylesheets support, inject it as an inline <style> tag:

import { styles } from "@fw-components/data-grid/styles";

const styleTag = document.createElement("style");
styleTag.textContent = styles;
document.head.appendChild(styleTag);

Quick Start

import { DataGrid } from "@fw-components/data-grid";
import type { ColumnDef } from "@fw-components/data-grid";

interface Asset {
  id: string;
  name: string;
  sector: string;
  value: number;
  irr: number;
}

const columns: ColumnDef<Asset>[] = [
  { accessorKey: "name", header: "Asset Name" },
  { accessorKey: "sector", header: "Sector" },
  {
    accessorKey: "value",
    header: "Value",
    meta: { formatType: "currency", formatOptions: { currencyCode: "USD" }, align: "right" },
  },
  {
    accessorKey: "irr",
    header: "IRR",
    meta: { formatType: "percentage", align: "right" },
  },
];

function PortfolioDashboard() {
  return (
    <DataGrid
      data={assets}
      columns={columns}
      getRowId={(row) => row.id}
      features={{ virtualization: true, sorting: true }}
      tableContainerClassName="h-[600px]"
    />
  );
}

Editing

Cell Editing

Enable editing on specific columns via meta.editable and meta.editType:

const columns: ColumnDef<Asset>[] = [
  {
    accessorKey: "name",
    header: "Asset Name",
    meta: { editable: true, editType: "text" },
  },
  {
    accessorKey: "sector",
    header: "Sector",
    meta: {
      editable: true,
      editType: "select",
      editOptions: [
        { value: "tech", label: "Technology" },
        { value: "health", label: "Healthcare" },
        { value: "finance", label: "Finance" },
      ],
    },
  },
  {
    accessorKey: "value",
    header: "Value",
    meta: { editable: true, editType: "number" },
  },
  {
    accessorKey: "investmentDate",
    header: "Date",
    meta: { editable: true, editType: "date" },
  },
  {
    accessorKey: "isActive",
    header: "Active",
    meta: { editable: true, editType: "boolean" },
  },
];

<DataGrid
  data={assets}
  columns={columns}
  getRowId={(row) => row.id}
  features={{ editing: true }}
  onCellEdit={async ({ rowId, columnId, value }) => {
    await api.updateAsset(rowId, { [columnId]: value });
  }}
  validateCell={(value, row, columnId) => {
    if (columnId === "name" && !value) return "Name is required";
    return null;
  }}
/>;

Custom Edit Components

For complex editors (e.g., entity pickers, async selects), use meta.editCell:

{
  accessorKey: "assignee",
  header: "Assignee",
  meta: {
    editable: true,
    editType: "custom",
    editCell: ({ value, onChange, onCommit, onCancel, error }) => (
      <UserPicker
        value={value}
        onChange={onChange}
        onSelect={(user) => { onChange(user); onCommit(); }}
        onCancel={onCancel}
        error={error}
      />
    ),
  },
}

Bulk Editing

Enable row selection, then commit an edit via onCellEdit for any row that's part of the current selection to apply it across all selected rows:

function PortfolioDashboard() {
  const [selectedIds, setSelectedIds] = useState<string[]>([]);

  const handleCellEdit = async ({ rowId, columnId, value, row }: CellEditEvent<Asset>) => {
    const isBulkTarget = selectedIds.length > 1 && selectedIds.includes(rowId);
    const targetIds = isBulkTarget ? selectedIds : [rowId];
    await Promise.all(targetIds.map((id) => api.updateAsset(id, { [columnId]: value })));
  };

  return (
    <DataGrid
      data={assets}
      columns={columns}
      getRowId={(row) => row.id}
      features={{ rowSelection: true, editing: true }}
      onCellEdit={handleCellEdit}
      onStateChange={{ onRowSelectionChange: setSelectedIds }}
    />
  );
}

Row Selection

<DataGrid
  data={assets}
  columns={columns}
  getRowId={(row) => row.id}
  features={{
    rowSelection: {
      enabled: true,
      columnPosition: "start",
      pinned: "left",
      width: 40,
      enableSelectAll: true,
    },
  }}
  onStateChange={{
    onRowSelectionChange: (selection) => console.log("Selected:", selection),
  }}
/>

Virtualization

Virtualization is enabled by default. For best performance with large datasets:

<DataGrid
  data={largeDataset} // 10,000+ rows
  columns={columns}
  getRowId={(row) => row.id}
  features={{ virtualization: true }}
  virtualizationConfig={{
    estimatedRowHeight: 48, // Helps virtualizer estimate scroll size
    overScan: 10,           // Extra rows rendered outside viewport
  }}
  tableContainerClassName="h-[80vh]" // Container must have a fixed height!
/>

⚠️ Important: The table container must have a fixed height (via className or style) for virtualization to work.

Column Formatting

Built-in formatters for financial data:

const columns: ColumnDef<Asset>[] = [
  {
    accessorKey: "marketValue",
    header: "Market Value",
    meta: {
      formatType: "currency",
      formatOptions: { currencyCode: "USD", numberFormat: "Millions", decimals: 1 },
      align: "right",
    },
  },
  {
    accessorKey: "irr",
    header: "IRR",
    meta: { formatType: "percentage", formatOptions: { decimals: 2 } },
  },
  {
    accessorKey: "multiple",
    header: "TVPI",
    meta: { formatType: "ratio" },
  },
  {
    accessorKey: "investmentDate",
    header: "Investment Date",
    meta: { formatType: "date", formatOptions: { dateFormat: "MMM DD, YYYY" } },
  },
];

Available format types: currency, percentage, decimal, number, text, date, ratio, boolean

Custom Format Function

{
  accessorKey: "logoUrl",
  header: "Logo",
  meta: {
    formatFn: (value) => <img src={value} className="w-8 h-8 rounded" alt="" />,
  },
}

API Reference

<DataGrid> Props

PropTypeDescription
dataTData[]Required. Array of row data
columnsColumnDef<TData>[]Required. Column definitions
getRowId(row, index) => stringStable row ID function (critical for editing/selection)
featuresDataGridFeaturesEnable/disable features
statePartial<TableState>Controlled state
onStateChangeTableStateHandlersState change callbacks
initialStatePartial<TableState>Initial state values
onCellEdit(event) => voidCell edit commit handler
validateCell(value, row, colId) => string | nullCell validation
onTableReady(table) => voidTanStack Table instance callback
onRowClick(row) => voidRow click handler
isLoadingbooleanShow loading state
emptyStateobjectEmpty state configuration
errorMessageReactNodeError state message
classNamestringOuter wrapper class
tableContainerClassNamestringScroll container class
getRowClassName(row, depth) => stringDynamic row styling

DataGridFeatures

interface DataGridFeatures {
  globalFilter?: boolean | { manual?: boolean };
  sorting?: boolean | { multi?: boolean; manual?: boolean };
  expanding?: boolean;
  columnResizing?: boolean;
  columnPinning?: boolean;
  virtualization?: boolean;
  rowSelection?: boolean | RowSelectionConfig;
  editing?: boolean | EditingConfig;
}

Column Meta

Extend column definitions with meta:

{
  editable?: boolean;
  editType?: "text" | "number" | "date" | "select" | "boolean" | "custom";
  editOptions?: { value: string; label: string }[];
  editCell?: (props: EditCellRenderProps) => ReactNode;
  validate?: (value, row) => string | null;
  formatType?: "currency" | "percentage" | "decimal" | "number" | "text" | "date" | "ratio" | "boolean";
  formatOptions?: FormatOptions;
  formatFn?: (value, cell) => ReactNode;
  align?: "left" | "center" | "right";
  width?: string | number;
  minWidth?: string | number;
  maxWidth?: string | number;
  headerClassName?: string;
  cellClassName?: string;
}

Hooks

useEditing(options)

Manages cell-level editing state. Stores drafts outside cell components for virtualization safety.

useDataGridState(options)

Central state management with controlled/uncontrolled support.

Keyboard Shortcuts

KeyAction
Enter / F2Start editing cell
EnterCommit edit
EscapeCancel edit
TabMove to next cell (when editing)
SpaceToggle checkbox / expand row

Showcase / Demo

Run the interactive showcase to try all features:

cd showcase/data-grid
npm install
npm run dev

Open http://localhost:5173 to see the portfolio dashboard demo with 500+ assets, editable columns, virtualization, and more.

Browser Support

  • Chrome/Edge 90+
  • Firefox 90+
  • Safari 15+

Contributing

See CONTRIBUTING.md for development setup and guidelines.

版本与发布记录

@fw-components/data-grid 共发布 24 个版本,首次发布于 2026/10/19;过去 12 个月发布了 24 个版本。最新版本附带 npm provenance 构建来源证明,可追溯到公开的 CI 构建记录。

版本发布日期距今
2.7.1latest2026/11/132 天前
2.7.1-grid-checkbox.0grid-checkbox2026/11/132 天前
2.7.02026/10/2917 天前
2.6.2-data-grid.16data-grid2026/10/2917 天前
2.6.2-data-grid.152026/10/2917 天前
2.6.2-data-grid.142026/10/2917 天前

关于 @fw-components/data-grid 的常见问题

@fw-components/data-grid 是什么?

A high-performance, editable data grid for React with built-in virtualization, sorting, filtering, and bulk editing.

如何安装 @fw-components/data-grid?

在项目目录运行 npm install @fw-components/data-grid,或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖:react(>=18.0.0)、react-dom(>=18.0.0)、@tanstack/react-table(^8.0.0)、@tanstack/react-virtual(^3.0.0)。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖,Yarn 需要手动安装。

@fw-components/data-grid 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@fw-components/data-grid 支持 ESM 还是 CommonJS?

以 ES Module 形式发布,推荐使用 import 引入。在 CommonJS 项目中,Node.js 20.19+ / 22.12+ 可以直接 require() 不含顶层 await 的 ES Module,更早的版本需要改用动态 import()。

@fw-components/data-grid 可以商用吗?

@fw-components/data-grid 使用 ISC 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@fw-components/data-grid 的下载量有多少?

根据 npm 官方下载统计,@fw-components/data-grid 在 2026/10/16 – 2026/11/14 这 30 天内被下载 3,674 次,日均约 122 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@fw-components/data-grid 还在维护吗?

最新版本 2.7.1 发布于 2026/11/13(2 天前);至今共发布 24 个版本,其中过去 12 个月发布了 24 个;首次发布于 2026/10/19。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。