react-datagrid-component
Version:
A powerful, customizable data grid component built with React, TypeScript, and TanStack Table v8
517 lines (421 loc) • 13.9 kB
Markdown
# FluentGrid - Advanced React Data Grid Component
A powerful, customizable data grid component built with React, TypeScript, and TanStack Table v8. Features include column resizing, pinning, filtering, sorting, pagination, cell editing, and theme support.
## 🚀 Features
- **📊 Advanced Data Grid**: Built on TanStack Table v8 for maximum performance
- **🎨 Theme Support**: Light/dark mode with custom primary colors
- **📏 Column Management**: Resize, pin, reorder, and hide columns
- **🔍 Smart Filtering**: Type-specific filters with advanced operators and global filter panel
- **✏️ Cell Editing**: Inline editing with validation and large text support
- **📱 Responsive Design**: Mobile-friendly with adaptive layouts
- **⚡ Virtual Scrolling**: Optimized for large datasets
- **🎯 Bulk Actions**: Multi-select with bulk operations
- **📤 Import/Export**: CSV and Excel support
- **🔧 Highly Customizable**: Extensive props and styling options
## 📦 Installation
```bash
npm install react-datagrid-component
# or
yarn add react-datagrid-component
# or
pnpm add react-datagrid-component
```
## ⚠️ **CRITICAL: Required Dependencies**
Make sure you have these peer dependencies installed:
```bash
npm install @tanstack/react-table react-resizable-panels
# or
yarn add @tanstack/react-table react-resizable-panels
# or
pnpm add @tanstack/react-table react-resizable-panels
```
## 🎨 Including Styles
**⚠️ IMPORTANT: You MUST import the CSS file for drag & drop and resize functionality to work:**
```tsx
import 'react-datagrid-component/dist/style.css';
```
**Without this CSS import, the following features will NOT work:**
- Column resizing (drag handles won't appear)
- Drag and drop column reordering
- Proper styling and interactions
The CSS file includes:
- Tailwind CSS utilities
- Component-specific styles
- Theme-aware styling
- Responsive design
- Accessibility features
- **Critical drag and resize handle styles**
## 🚨 Troubleshooting: Drag & Drop / Resize Not Working?
If drag and drop or column resize functionality isn't working in your project:
### **1. Check CSS Import**
```tsx
// ✅ Make sure you have this import
import 'react-datagrid-component/dist/style.css';
```
### **2. Check Dependencies**
```bash
# Make sure these are installed
npm install @tanstack/react-table react-resizable-panels
```
### **3. Check Your Build Configuration**
If you're using a bundler that doesn't handle CSS imports automatically, you may need to:
**For Vite:**
```javascript
// vite.config.js
export default defineConfig({
optimizeDeps: {
include: ['react-datagrid-component']
}
})
```
**For Webpack:**
```javascript
// webpack.config.js
module: {
rules: [
{
test: /\.css$/,
use: ['style-loader', 'css-loader']
}
]
}
```
### **4. Manual CSS Import**
If automatic CSS import isn't working, you can manually copy the styles:
```css
/* Add these critical styles to your CSS */
.column-resize-handle {
position: absolute;
right: 0;
top: 0;
height: 100%;
width: 4px;
cursor: col-resize;
user-select: none;
touch-action: none;
z-index: 10;
transition: all 0.2s ease;
background-color: transparent;
}
.column-resize-handle:hover {
width: 6px;
background-color: hsl(var(--primary) / 0.2);
border-right: 1px solid hsl(var(--primary) / 0.3);
}
.drag-handle {
cursor: grab;
transition: all 0.2s ease;
opacity: 0.6;
pointer-events: auto;
z-index: 5;
}
.drag-handle:hover {
opacity: 1;
background-color: hsl(var(--muted) / 0.5);
}
.drag-handle:active {
cursor: grabbing;
background-color: hsl(var(--primary) / 0.1);
}
```
## 🎯 Quick Start
```tsx
import { DataGridTable } from 'react-datagrid-component';
// ⚠️ CRITICAL: Import CSS for functionality
import 'react-datagrid-component/dist/style.css';
const columns = [
{
id: 'name',
header: 'Name',
accessorKey: 'name',
type: 'text',
editable: true,
},
{
id: 'age',
header: 'Age',
accessorKey: 'age',
type: 'number',
sortable: true,
},
{
id: 'status',
header: 'Status',
accessorKey: 'status',
type: 'badge',
options: [
{ label: 'Active', value: 'active' },
{ label: 'Inactive', value: 'inactive' },
],
},
];
const data = [
{ id: 1, name: 'John Doe', age: 30, status: 'active' },
{ id: 2, name: 'Jane Smith', age: 25, status: 'inactive' },
];
function App() {
return (
<DataGridTable
data={data}
columns={columns}
tableName="Users"
onDataChange={(newData) => console.log('Data changed:', newData)}
/>
);
}
```
## 📚 API Reference
### DataGridTable Props
| Prop | Type | Default | Description |
|------|------|---------|-------------|
| `data` | `T[]` | - | Array of data objects |
| `columns` | `DataGridColumn<T>[]` | - | Column definitions |
| `tableName` | `string` | - | Display name for the table |
| `loading` | `boolean` | `false` | Loading state |
| `error` | `string` | - | Error message to display |
| `onDataChange` | `(data: T[]) => void` | - | Callback when data changes |
| `onRowEdit` | `(row: T, field: keyof T, value: any) => Promise<void>` | - | Row edit callback |
| `onRowDelete` | `(rows: T[]) => Promise<void>` | - | Row delete callback |
| `onExport` | `(data: T[], format: 'csv' \| 'xlsx') => void` | - | Export callback |
| `onImport` | `(data: T[]) => void` | - | Import callback |
| `pagination` | `PaginationConfig` | `{ pageSize: 25, showSizeSelect: true, pageSizeOptions: [10, 25, 50, 100] }` | Pagination settings |
| `selection` | `SelectionConfig` | `{ enabled: true }` | Row selection settings |
| `globalSearch` | `GlobalSearchConfig` | `{ enabled: true, placeholder: "Search across all columns..." }` | Global search settings |
| `theming` | `ThemingConfig` | `{ enabled: true, defaultTheme: 'light' }` | Theme settings |
| `className` | `string` | - | Additional CSS classes |
| `apiConfig` | `DataGridApiConfig` | - | API configuration for CRUD operations |
### Column Types
| Type | Description | Features |
|------|-------------|----------|
| `text` | Text input | Basic text editing, filtering |
| `number` | Numeric input | Number validation, range filtering |
| `select` | Dropdown selection | Predefined options, multi-select |
| `date` | Date picker | Date range filtering, calendar |
| `badge` | Status badges | Color-coded status display |
| `image` | Image display | Thumbnail preview |
| `chart` | Chart visualization | Data visualization |
| `largeText` | Large text editor | Multi-line editing, popup editor |
### Column Properties
| Property | Type | Description |
|----------|------|-------------|
| `id` | `string` | Unique column identifier |
| `header` | `string` | Column header text |
| `accessorKey` | `keyof T` | Data field key |
| `type` | `ColumnType` | Column type for rendering |
| `editable` | `boolean` | Enable cell editing |
| `filterable` | `boolean` | Enable column filtering |
| `sortable` | `boolean` | Enable column sorting |
| `pinnable` | `boolean` | Enable column pinning |
| `width` | `number` | Column width in pixels |
| `minWidth` | `number` | Minimum column width |
| `maxWidth` | `number` | Maximum column width |
| `options` | `Array<{label: string, value: any}>` | Options for select/badge types |
## 🎨 Styling
The component uses Tailwind CSS for styling and includes comprehensive CSS classes. You can customize the appearance in several ways:
### 1. CSS Import (Required)
```tsx
import 'react-datagrid-component/dist/style.css';
```
### 2. Theme Variables
Override CSS custom properties for theming:
```css
:root {
--primary: 20 14.3% 4.1%;
--primary-foreground: 60 9.1% 97.8%;
--background: 0 0% 100%;
--foreground: 20 14.3% 4.1%;
--muted: 210 40% 96%;
--muted-foreground: 215.4 16.3% 46.9%;
--border: 214.3 31.8% 91.4%;
--ring: 215 20.2% 65.1%;
/* ... more variables */
}
```
### 3. Custom Classes
Pass additional CSS classes via the `className` prop:
```tsx
<DataGridTable
data={data}
columns={columns}
className="my-custom-grid bg-blue-50"
/>
```
### 4. Component-Specific Classes
The CSS includes utility classes for specific components:
```css
.fluent-grid-badge.active { /* Active badge styles */ }
.fluent-grid-avatar { /* Avatar styles */ }
.fluent-grid-progress { /* Progress bar styles */ }
.fluent-grid-search { /* Search input styles */ }
```
### 5. Tailwind Configuration
Extend your Tailwind configuration to include the component's design tokens:
```js
// tailwind.config.js
module.exports = {
content: [
'./src/**/*.{js,ts,jsx,tsx}',
'node_modules/react-datagrid-component/dist/**/*.js'
],
theme: {
extend: {
colors: {
// Your custom colors
}
}
}
}
```
## 🔧 Advanced Usage
### Custom Cell Renderers
```tsx
import { CellRenderer } from 'fluent-grid';
const CustomCell = ({ value, row, column, isEditing, onSave, onCancel }) => {
if (isEditing) {
return (
<input
value={value}
onChange={(e) => onSave(e.target.value)}
onBlur={onCancel}
autoFocus
/>
);
}
return <span>{value}</span>;
};
const columns = [
{
id: 'custom',
header: 'Custom',
accessorKey: 'custom',
cell: CustomCell,
},
];
```
### API Integration
```tsx
const apiConfig = {
fetchUrl: 'https://api.example.com/users',
updateUrl: 'https://api.example.com/users/:id',
deleteUrl: 'https://api.example.com/users',
method: 'PATCH',
};
<DataGridTable
data={data}
columns={columns}
apiConfig={apiConfig}
onRowEdit={async (row, field, value) => {
// Custom edit logic
await updateUser(row.id, { [field]: value });
}}
/>
```
### Custom Filtering
```tsx
const columns = [
{
id: 'status',
header: 'Status',
accessorKey: 'status',
type: 'select',
filterable: true,
options: [
{ label: 'Active', value: 'active' },
{ label: 'Inactive', value: 'inactive' },
{ label: 'Pending', value: 'pending' },
],
},
];
```
### Global Filter Panel
The global filter panel provides a centralized filtering experience with multiple filter rows, supporting AND/OR logic combinations.
```tsx
<DataGridTable
data={data}
columns={columns}
globalFilter={{
enabled: true, // Enable global filter panel
}}
/>
```
**Features:**
- **Multiple Filter Rows**: Add unlimited filter conditions
- **Column Selection**: Choose from available columns
- **Type-Specific Operators**: Operators adapt to column type
- **AND/OR Logic**: Combine filters with logical operators
- **Value Inputs**: Type-appropriate input controls (text, number, date, select)
- **Real-time Validation**: Only valid filters are applied
- **Clear All**: Remove all filters at once
**Supported Operators by Type:**
| Column Type | Operators |
|-------------|-----------|
| `text` | contains, not contains, starts with, ends with, equals, not equals, in, not in |
| `number` | equals, not equals, greater than, greater than or equal, less than, less than or equal, between |
| `date` | equals, not equals, after, on or after, before, on or before, between |
| `select`/`badge` | equals, not equals, in, not in |
**Example Usage:**
```tsx
// Filter users who are active AND age > 25 OR email contains "@gmail.com"
// This would be configured in the global filter panel with:
// Filter 1: Status = Active AND Age > 25
// Filter 2: Email contains "@gmail.com" (OR logic)
```
## 📦 Exported Components
- `DataGridTable` - Main data grid component
- `ThemePicker` - Theme selection component
- `FileUpload` - Import/export component
- `ColumnVisibility` - Column visibility toggle
- `ColumnFilter` - Individual column filter
- `GlobalFilterPanel` - Global filter panel component
- `AppliedFilters` - Active filters display
- `BulkActions` - Bulk operations component
- `TablePagination` - Pagination component
- `CellRenderer` - Cell rendering utilities
- `DensitySelector` - Row density selector
- `PinnedColumnsIndicator` - Pinned columns display
- `LargeTextEditor` - Large text editing dialog
- `ResizablePopup` - Resizable popup component
## 🔗 Dependencies
### Peer Dependencies
- `react` ^18.0.0
- `react-dom` ^18.0.0
- `@tanstack/react-table` ^8.0.0
### Required Dependencies
- `@radix-ui/*` - UI primitives
- `lucide-react` - Icons
- `date-fns` - Date utilities
- `react-day-picker` - Date picker
- `class-variance-authority` - Component variants
- `clsx` - Conditional classes
- `tailwind-merge` - Tailwind class merging
## 🤝 Contributing
1. Fork the repository
2. Create a feature branch
3. Make your changes
4. Add tests if applicable
5. Submit a pull request
## 📄 License
MIT License - see LICENSE file for details
## 🔧 Troubleshooting
### CSS Import Issues
If you encounter an error like:
```
Failed to resolve import "react-datagrid-component/dist/style.css"
```
**Solution**: Make sure you're importing the CSS file correctly:
```tsx
import 'react-datagrid-component/dist/style.css';
```
**Common issues**:
1. **Missing CSS import**: Always import the CSS file after installing the package
2. **Build tool configuration**: Ensure your bundler (Vite, Webpack, etc.) can handle CSS imports
3. **Package version**: Make sure you're using the latest version of the package
### Styling Issues
If the component doesn't look styled properly:
1. **Check CSS import**: Ensure the CSS file is imported
2. **Tailwind CSS**: Make sure Tailwind CSS is installed and configured in your project
3. **CSS variables**: Verify that your CSS custom properties are defined
### Build Issues
If you encounter build errors:
1. **Peer dependencies**: Ensure all peer dependencies are installed
2. **TypeScript**: Make sure TypeScript is configured to handle the package types
3. **Module resolution**: Check that your bundler can resolve ES modules