1.0.23 β€’ Published 4 months ago

kimia-grid v1.0.23

Weekly downloads
-
License
KSL
Repository
-
Last release
4 months ago

K-Grid

A lightweight, customizable React data grid component built on top of TanStack Table and MUI Joy UI.

Features

  • πŸ” Built-in search and filtering capabilities
  • πŸ”„ Column sorting with visual indicators
  • πŸ“ Customizable column widths
  • 🎨 Clean, modern UI based on Joy UI
  • 🧩 Fully typed with TypeScript
  • πŸ”Œ Extensible API for custom functionality
  • πŸ•ΆοΈ Column visibility control with hide property
  • πŸ†” Automatic column ID resolution from accessorKey or header
  • πŸ“„ Pagination with customizable page sizes

Installation

# npm
npm install kimia-grid

# yarn
yarn add kimia-grid

# pnpm
pnpm add kimia-grid

Basic Usage

import { useRef } from 'react';
import { KGrid, KColumnDef, GridApi } from 'k-grid';

// Define your data type
type User = {
  id: string;
  name: string;
  email: string;
};

// Sample data
const users: User[] = [
  { id: '1', name: 'John Doe', email: 'john@example.com' },
  { id: '2', name: 'Jane Smith', email: 'jane@example.com' },
  { id: '3', name: 'Bob Johnson', email: 'bob@example.com' },
];

// Define columns
const columns: KColumnDef<User>[] = [
  {
    header: 'ID',
    accessorKey: 'id',
    width: 70, // Fixed width in pixels
  },
  {
    header: 'Name',
    accessorKey: 'name',
    minWidth: 200, // Minimum width
  },
  {
    header: 'Email',
    accessorKey: 'email',
    maxWidth: 300, // Maximum width
    hide: true, // This column will be hidden by default
  },
];

function App() {
  const gridApi = useRef<GridApi>(null);

  return (
    <div style={{ height: '400px', width: '100%' }}>
      <KGrid 
        ref={gridApi}
        rowData={users} 
        columns={columns} 
        pagination={true}
        paginationOptions={[10, 20, 50]}
      />
    </div>
  );
}

Advanced Features

Pagination

K-Grid supports client-side pagination with customizable page sizes:

<KGrid
  rowData={data}
  columns={columns}
  pagination={true}
  paginationSize={20} // Default page size
  paginationOptions={[10, 20, 50, 100]} // Available page size options
/>

The pagination controls include:

  • Page size selector
  • Previous/next page buttons
  • Automatic row count calculation

Column Visibility Control

You can control column visibility using the hide property in column definitions:

const columns: KColumnDef<User>[] = [
  {
    header: 'ID',
    accessorKey: 'id',
    hide: true, // This column will be hidden by default
  },
  {
    header: 'Name',
    accessorKey: 'name',
  },
  // ...other columns
];

The column ID is automatically resolved in this order: 1. Explicit id property 2. accessorKey (if provided) 3. header string (if provided)

Global Search

import { useRef } from 'react';
import { Input } from '@mui/joy';
import { KGrid, GridApi } from 'k-grid';

function App() {
  const gridApi = useRef<GridApi>(null);

  const handleSearch = (searchText: string) => {
    if (gridApi.current) {
      gridApi.current.setGlobalFilter(searchText);
    }
  };

  return (
    <div>
      <Input
        placeholder="Search..."
        onChange={(e) => handleSearch(e.target.value)}
      />
      <KGrid 
        ref={gridApi}
        rowData={data} 
        columns={columns} 
      />
    </div>
  );
}

Column Filtering

Column filtering is enabled by default. To enable filtering for specific columns:

const columns: KColumnDef<User>[] = [
  {
    header: 'Name',
    accessorKey: 'name',
    enableColumnFilter: true, // Enable filtering for this column
  },
  // ...other columns
];

Custom Sorting

const columns: KColumnDef<User>[] = [
  {
    header: 'Created Date',
    accessorKey: 'createdAt',
    sortingFn: 'datetime', // Use built-in datetime sorting
  },
  // ...other columns
];

// Set default sorting
<KGrid 
  rowData={data} 
  columns={columns} 
  defaultSorting={[{ id: 'createdAt', desc: true }]}
/>

Column Width Configuration

const columns: KColumnDef<User>[] = [
  {
    header: 'ID',
    accessorKey: 'id',
    width: 70, // Fixed width in pixels
  },
  {
    header: 'Actions',
    cell: () => <EditIcon size={14} />,
    width: 50, // Narrow column for icons
    enableSorting: false,
  },
  {
    header: 'Name',
    accessorKey: 'name',
    minWidth: 200, // Minimum width
  },
  {
    header: 'Description',
    accessorKey: 'description',
    maxWidth: 400, // Maximum width
  },
];

Striped Rows

<KGrid 
  rowData={data} 
  columns={columns} 
  stripe="odd" // or "even"
/>

Empty State Handling

K-Grid provides a customizable empty state when no data is available:

<KGrid
  rowData={[]}
  columns={columns}
  noDataComponent={
    <Box sx={{ textAlign: 'center' }}>
      <Typography level="h4" sx={{ mb: 1 }}>
        No se encontraron resultados
      </Typography>
      <Typography level="body-md">
        Intenta ajustar tus filtros de bΓΊsqueda
      </Typography>
    </Box>
  }
/>

You can also use a simple string:

<KGrid
  rowData={[]}
  columns={columns}
  noDataComponent="No data available"
/>

If no noDataComponent is provided, a default message will be shown.

Expandable Rows

K-Grid supports expandable rows with custom sub-components:

// Define a column with an expander button
const columns: KColumnDef<User>[] = [
  {
    id: 'expander',
    header: '',
    width: 40,
    cell: ({ row }) => (
      <IconButton
        size="sm"
        variant="plain"
        onClick={() => row.toggleExpanded()}
      >
        {row.getIsExpanded() ? <ChevronDown /> : <ChevronRight />}
      </IconButton>
    ),
  },
  // ... other columns
];

// Define a sub-component to render when a row is expanded
const SubComponent = ({ row }: { row: Row<User> }) => {
  const data = row.original;
  
  return (
    <Card variant="outlined" sx={{ m: 1 }}>
      <Typography>Additional details for {data.name}</Typography>
      {/* More content here */}
    </Card>
  );
};

// Use the renderSubComponent prop
<KGrid 
  rowData={data} 
  columns={columns} 
  renderSubComponent={SubComponent}
  defaultExpanded={false} // Optional: set to true to expand all rows by default
/>

This implementation gives you complete control over how rows are expanded. You can:

  1. Add an expander column with custom styling and behavior
  2. Define what content appears when a row is expanded
  3. Control the initial expansion state
  4. Access all row data and methods in both the cell renderer and sub-component

API Reference

KGrid Props

PropTypeDescription
rowDataT[]Array of data objects to display in the grid
columnsKColumnDef<T>[]Column definitions
defaultSortingSortingStateInitial sorting state
globalFilterstringInitial global filter value
stripe"odd" \| "even"Row striping pattern
renderSubComponent(props: { row: Row<T> }) => ReactNodeFunction to render content when a row is expanded
defaultExpandedbooleanWhether all rows should be expanded by default
paginationbooleanEnable pagination
paginationSizenumberDefault page size
paginationIndexnumberInitial page index
paginationOptionsnumber[]Available page size options
noDataComponentReactNodeComponent or message to display when no data is available

KColumnDef

Extends all properties from TanStack Table's ColumnDef with additional properties:

PropertyTypeDescription
widthnumber \| stringFixed width for the column
minWidthnumber \| stringMinimum width for the column
maxWidthnumber \| stringMaximum width for the column
hidebooleanWhether the column should be hidden by default
accessorKeystringKey to access data in the row object

GridApi

MethodDescription
setGlobalFilter(filter: string)Set the global filter value
getGlobalFilter()Get the current global filter value

License

KSL

1.0.23

4 months ago

1.0.22

4 months ago

1.0.21

4 months ago

1.0.20

4 months ago

1.0.19

4 months ago

1.0.18

4 months ago

1.0.17

4 months ago

1.0.16

4 months ago

1.0.15

4 months ago

1.0.14

4 months ago

1.0.13

4 months ago

1.0.12

4 months ago

1.0.11

4 months ago

1.0.10

4 months ago

1.0.9

4 months ago

1.0.8

4 months ago

1.0.7

4 months ago

1.0.6

4 months ago

1.0.5

4 months ago

1.0.4

4 months ago

1.0.3

4 months ago