Skip to content

marafa1985/data-grid

Repository files navigation

Advanced Data Grid Component

A powerful, feature-rich data grid component built with React and TypeScript. This component provides advanced filtering, grouping, column management, export capabilities, and much more.

Features

  • 🔍 Advanced Filtering - Text, date range, number range, and multi-select filters
  • 📊 Smart Grouping - Multi-level grouping with templates and aggregations
  • 🎛️ Column Management - Show/hide, pin, resize, and reorder columns
  • 📤 Export Options - Export to CSV, Excel, JSON, XML, PDF, HTML, SQL, Markdown, and Text
  • ⌨️ Keyboard Shortcuts - Comprehensive keyboard navigation and actions
  • 🎨 Customization - Custom renderers, grouped headers, and themes
  • 📱 Responsive - Works on desktop, tablet, and mobile devices
  • Accessible - WCAG compliant with screen reader support

Installation

```bash npm install @/components/data-grid ```

Basic Usage

```tsx import DataGrid from '@/components/data-grid'

const columns = [ { key: 'id', title: 'ID', type: 'number' }, { key: 'name', title: 'Name', type: 'text', sortable: true, filterable: true }, { key: 'email', title: 'Email', type: 'text', filterable: true }, { key: 'salary', title: 'Salary', type: 'currency', sortable: true, filterable: true } ]

const data = [ { id: 1, name: 'John Doe', email: 'john@example.com', salary: 75000 }, { id: 2, name: 'Jane Smith', email: 'jane@example.com', salary: 85000 } ]

function MyComponent() { return ( ) } ```

Props

Prop Type Default Description
data any[] Required Array of data objects to display
columns Column[] Required Column configuration array
pageSize number 10 Number of rows per page
allowSelection boolean false Enable row selection with checkboxes
allowGrouping boolean false Enable drag-and-drop grouping
allowExport boolean false Enable export functionality
allowColumnResize boolean false Enable column resizing
allowColumnReorder boolean false Enable column reordering
onColumnOrderChange (order: string[]) => void - Callback when column order changes

Column Configuration

```tsx interface Column { key: string // Unique identifier for the column title: string // Display title in header sortable?: boolean // Enable sorting for this column filterable?: boolean // Enable filtering for this column width?: number // Initial column width in pixels type?: 'text' | 'number' | 'date' | 'currency' // Data type for formatting filterType?: 'text' | 'dateRange' | 'numberRange' | 'multiSelect' filterOptions?: string[] // Options for multiSelect filter columns?: Column[] // Sub-columns for grouped headers render?: (row: any) => React.ReactNode // Custom cell renderer pinnable?: boolean // Allow pinning this column } ```

Column Types

  • text: Plain text with string filtering
  • number: Numeric values with range filtering
  • date: Date values with date range filtering
  • currency: Formatted currency values with range filtering

Filter Types

  • text: Simple text search
  • dateRange: Date range picker with from/to dates
  • numberRange: Number range with min/max inputs
  • multiSelect: Dropdown with multiple selection options

Advanced Features

Filtering

The data grid supports multiple filter types and operators:

```tsx // Text filter - searches within text content { key: 'name', title: 'Name', type: 'text', filterable: true }

// Date range filter - filter between two dates { key: 'createdAt', title: 'Created', type: 'date', filterType: 'dateRange', filterable: true }

// Number range filter - filter between min/max values { key: 'salary', title: 'Salary', type: 'currency', filterType: 'numberRange', filterable: true }

// Multi-select filter - select from predefined options { key: 'status', title: 'Status', type: 'text', filterType: 'multiSelect', filterOptions: ['Active', 'Inactive', 'Pending'], filterable: true } ```

Filter Operators

  • AND: All filters must match (default)
  • OR: Any filter can match
  • Switch between operators using the filter summary panel

Filter History

  • Undo: Ctrl+Z or use the undo button
  • Redo: Ctrl+Y or Ctrl+Shift+Z
  • Clear All: Delete key or clear all button

Grouping

Enable grouping by setting allowGrouping={true}:

  1. Drag columns from the header to the grouping panel
  2. Multi-level grouping - drag multiple columns for nested groups
  3. Group templates - customize how group headers appear
  4. Aggregations - show sum, average, min, max, count for grouped data

Group Templates

```tsx // Built-in templates

  • Default: "{{groupKey}}: {{groupValue}} ({{itemCount}} items)"
  • Compact: "{{groupValue}} ({{itemCount}})"
  • Detailed: "{{groupKey}}: {{groupValue}} | {{itemCount}} items | Total: {{sum_salary}}"

// Custom template variables

  • {{groupKey}} - Column title
  • {{groupValue}} - Group value
  • {{itemCount}} - Number of items in group
  • {{sum_columnName}} - Sum aggregation
  • {{avg_columnName}} - Average aggregation
  • {{min_columnName}} - Minimum value
  • {{max_columnName}} - Maximum value
  • {{count_columnName}} - Count of non-null values
  • {{uniqueCount_columnName}} - Count of unique values ```

Column Management

Visibility Control

  • Individual: Toggle columns on/off
  • Bulk operations: Show/hide selected columns
  • Type-based: Show only numbers, text, or dates
  • Presets: Essential columns only

Column Pinning

  • Left pinning: Keep columns visible on the left
  • Right pinning: Keep columns visible on the right
  • Visual indicators: Pinned columns have distinct borders

Column Resizing

  • Manual: Drag column borders to resize
  • Auto-size: Automatically fit content
  • Distribute: Evenly distribute available width

Column Reordering

  • Drag and drop: Drag column headers to reorder
  • Management panel: Use up/down arrows in column panel
  • Restrictions: Pinned columns cannot be reordered

Export Options

Export data in multiple formats with customization options:

Supported Formats

  1. CSV - Comma-separated values
  2. Excel - Microsoft Excel format (.xlsx)
  3. JSON - JavaScript Object Notation
  4. XML - Extensible Markup Language
  5. PDF - Portable Document Format
  6. HTML - HTML table format
  7. SQL - SQL INSERT statements
  8. Markdown - Markdown table format
  9. Text - Plain text table

Export Options

  • Data scope: All data, filtered data, selected rows, or visible rows
  • Column selection: Choose which columns to include
  • Headers: Include/exclude column headers
  • Formatting: Custom date formats, number formats, delimiters
  • File naming: Custom filename with timestamp

Keyboard Shortcuts

General Actions

  • ? - Show keyboard shortcuts help
  • Esc - Close dialogs and clear selection
  • Ctrl+F - Focus global search
  • Delete - Clear all filters

Selection

  • Ctrl+A - Select/deselect all rows

Navigation

  • J - Next page
  • K - Previous page
  • Home - First page
  • End - Last page
  • Alt+N - Next page (alternative)
  • Alt+P - Previous page (alternative)
  • Alt+1 - First page (alternative)
  • Alt+0 - Last page (alternative)

Panels

  • Alt+C - Toggle columns panel
  • Alt+F - Toggle advanced settings panel
  • Ctrl+E - Open export dialog

View Options

  • Alt+M - Toggle compact mode
  • Alt+R - Toggle row numbers
  • Alt+S - Toggle summary row
  • Alt+H - Toggle all rows visibility
  • Alt+G - Toggle all groups (expand/collapse)

History

  • Ctrl+Z - Undo filter changes
  • Ctrl+Y - Redo filter changes
  • Ctrl+Shift+Z - Redo filter changes (alternative)

Custom Renderers

Create custom cell content with the render function:

```tsx const columns = [ { key: 'status', title: 'Status', render: (row) => ( <Badge variant={row.status === 'Active' ? 'success' : 'secondary'}> {row.status} ) }, { key: 'progress', title: 'Progress', render: (row) => (

<div className="bg-blue-600 h-2 rounded-full" style={{ width: ${row.progress}% }} />
{row.progress}%
) } ] ```

Grouped Headers

Organize columns into logical sections:

```tsx const columns = [ { key: 'personal', title: 'Personal Information', columns: [ { key: 'name', title: 'Name', type: 'text' }, { key: 'email', title: 'Email', type: 'text' } ] }, { key: 'employment', title: 'Employment Details', columns: [ { key: 'department', title: 'Department', type: 'text' }, { key: 'salary', title: 'Salary', type: 'currency' } ] } ] ```

API Reference

Interfaces

```tsx interface Column { key: string title: string sortable?: boolean filterable?: boolean width?: number type?: "text" | "number" | "date" | "currency" filterType?: "text" | "dateRange" | "numberRange" | "multiSelect" filterOptions?: string[] columns?: Column[] render?: (row: any) => React.ReactNode pinnable?: boolean }

interface DataGridProps { data: any[] columns: Column[] pageSize?: number allowSelection?: boolean allowGrouping?: boolean allowExport?: boolean allowColumnResize?: boolean allowColumnReorder?: boolean onColumnOrderChange?: (newOrder: string[]) => void }

interface FilterPreset { id: string name: string filters: Record<string, any> filterOperator: "AND" | "OR" createdAt: string }

interface GroupConfig { columnKey: string title: string sortDirection: "asc" | "desc" expanded: boolean } ```

Best Practices

Performance

  1. Virtualization: For large datasets (>1000 rows), consider implementing virtual scrolling
  2. Memoization: Use React.memo for custom renderers with complex logic
  3. Debouncing: Filter inputs are debounced to prevent excessive re-renders
  4. Pagination: Use reasonable page sizes (10-100 rows)

User Experience

  1. Loading states: Show loading indicators during data fetching
  2. Empty states: Provide helpful messages when no data is available
  3. Error handling: Display user-friendly error messages
  4. Responsive design: Test on different screen sizes
  5. Accessibility: Ensure keyboard navigation works properly

Data Management

  1. Consistent data types: Ensure column types match your data
  2. Unique keys: Use unique identifiers for row keys
  3. Null handling: Handle null/undefined values gracefully
  4. Date formats: Use consistent date formats (ISO 8601 recommended)

Troubleshooting

Common Issues

Q: Columns are not sortable A: Ensure sortable: true is set in the column configuration

Q: Filters are not working A: Check that filterable: true is set and the column type matches your data

Q: Export is not available A: Set allowExport={true} in the DataGrid props

Q: Drag and drop grouping doesn't work A: Enable grouping with allowGrouping={true} and ensure columns are draggable

Q: Column resizing is not working A: Set allowColumnResize={true} in the DataGrid props

Q: Performance is slow with large datasets A: Consider implementing pagination or virtual scrolling for datasets >1000 rows

Browser Compatibility

  • Chrome 90+
  • Firefox 88+
  • Safari 14+
  • Edge 90+

Accessibility

The component follows WCAG 2.1 guidelines:

  • Keyboard navigation support
  • Screen reader compatibility
  • High contrast mode support
  • Focus management
  • ARIA labels and roles

Examples

See the example files for complete implementations:

  • examples/simple-example.tsx - Basic product catalog
  • examples/basic-example.tsx - Employee directory with all features
  • examples/advanced-example.tsx - Sales dashboard with custom renderers

Contributing

  1. Fork the repository
  2. Create a feature branch
  3. Make your changes
  4. Add tests
  5. Submit a pull request

License

MIT License - see LICENSE file for details

About

A powerful, feature-rich data grid component built with React and TypeScript. This component provides advanced filtering, grouping, column management, export capabilities, and much more.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

No releases published

Packages

 
 
 

Contributors