npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@svipulc/custom-ts-table

v1.0.3

Published

[![npm version](https://img.shields.io/npm/v/@svipulc/custom-ts-table.svg?style=flat-square)](https://www.npmjs.com/package/@svipulc/custom-ts-table) [![TypeScript](https://img.shields.io/badge/TypeScript-Ready-blue?style=flat-square&logo=typescript)](htt

Downloads

32

Readme

🚀 Custom Table

npm version TypeScript React

Unleash the power of flexible, type-safe tables in your React applications! 🎉

Table of Contents

🌟 Features

  • 🔒 Type-safe: Leverage TypeScript for compile-time checks
  • 🧩 Modular: Use the hook or the ready-made component
  • 🔍 Powerful filtering: Global and column-specific filtering
  • 🔢 Pagination: Built-in support for paginated data
  • 🔀 Sorting: Easy-to-use sorting capabilities
  • 👥 Grouped columns: Organize your data logically
  • 🎨 Custom rendering: Flexible cell and header rendering
  • 🚀 Performance optimized: Efficient even with large datasets

📦 Installation

npm install @svipulc/custom-ts-table
# or
yarn add @svipulc/custom-ts-table

🚀 Quick Start

Here's a basic example of how to use the useTable hook:

import { useTable, createColumnHelper } from '@svipulc/custom-ts-table';

interface Employee {
  id: string;
  name: string;
  salary: number;
  department: string;
}

const columnHelper = createColumnHelper<Employee>();

const columns = [
  columnHelper.accessor('id', {
    header: 'Employee ID',
    footer: 'Total Employees',
  }),
  columnHelper.accessor('name', {
    header: 'Full Name',
  }),
  columnHelper.accessor('salary', {
    header: 'Salary',
    cell: (info) => `$${info.getValue().toLocaleString()}`,
  }),
  columnHelper.accessor('department', {
    header: 'Department',
  }),
];

const MyAwesomeTable = () => {
  const table = useTable({
    data: employees,
    columns: columns,
  });

  const { getHeaderGroups, getRowModel, getFooterGroups } = table;

  return (
    <table>
      <thead>
        {getHeaderGroups().map((headerGroup) => (
          <tr key={headerGroup.id}>
            {headerGroup.headers.map((header) => (
              <th key={header.id}>{header.isPlaceholder ? null : header.renderHeader()}</th>
            ))}
          </tr>
        ))}
      </thead>
      <tbody>
        {getRowModel().rows.map((row) => (
          <tr key={row.id}>
            {row.getVisibleCells().map((cell) => (
              <td key={cell.id}>{cell.renderCell()}</td>
            ))}
          </tr>
        ))}
      </tbody>
      <tfoot>
        {getFooterGroups().map((footerGroup) => (
          <tr key={footerGroup.id}>
            {footerGroup.headers.map((header) => (
              <td key={header.id}>{header.isPlaceholder ? null : header.renderFooter()}</td>
            ))}
          </tr>
        ))}
      </tfoot>
    </table>
  );
};

📖 API Reference

useTable Hook

The main hook that creates and manages the table instance.

const table = useTable<T>(options: TableOptions<T>)

Options

interface TableOptions<T> {
  data: T[];
  columns: Column<T>[];
  sorting?: {
    key: DeepKeys<T>;
    direction: "ascending" | "descending" | "none";
  } | null;
  globalFilter?: string;
  columnFilter?: Record<string, (value: any) => boolean>;
  pagination?: {
    page: number;
    pageSize: number;
  };
}

Returns

The hook returns a table instance with the following methods:

| Method | Description | | --------------------- | ----------------------------------------------------------------- | | getHeaderGroups() | Returns header groups including grouped columns | | getRowModel() | Returns the current row model with pagination applied | | getFooterGroups() | Returns footer groups | | getPaginationInfo() | Returns pagination details including total pages and current page |

Column Helper

The createColumnHelper utility provides a type-safe way to define columns:

const columnHelper = createColumnHelper<T>();

// Create an accessor column
columnHelper.accessor(key, {
  id?: string;
  header?: string | (() => React.ReactNode);
  footer?: string | (() => React.ReactNode);
  cell?: (info: CellContext<T>) => React.ReactNode;
});

🎯 Advanced Features

Sorting

const [sortConfig, setSortConfig] = useState<{
  key: DeepKeys<DataType>;
  direction: "ascending" | "descending" | "none";
} | null>(null);

const table = useTable({
  // ... other options
  sorting: sortConfig,
});

Filtering

// Global filtering
const [globalFilter, setGlobalFilter] = useState("");

// Column-specific filtering
const columnFilters = {
  price: (value: number) => value < 100,
  stock: (value: number) => value > 0,
};

const table = useTable({
  // ... other options
  globalFilter: globalFilter,
  columnFilter: columnFilters,
});

Pagination

const [currentPage, setCurrentPage] = useState(1);
const [pageSize, setPageSize] = useState(10);

const table = useTable({
  // ... other options
  pagination: {
    page: currentPage,
    pageSize: pageSize,
  },
});

// Access pagination info
const { totalPages, currentPage, totalItems } = table.getPaginationInfo();

Grouped Columns

const columns = [
  // ... regular columns
  columnHelper.group({
    id: "dimensions",
    header: "Dimensions",
    columns: [
      columnHelper.accessor("width", {
        header: "Width",
      }),
      columnHelper.accessor("height", {
        header: "Height",
      }),
    ],
  }),
];

Custom Cell Rendering

columnHelper.accessor('stock', {
  cell: info => {
    if (info.getValue() <= 10) {
      return <span style={{ color: 'red' }}>{info.getValue()}</span>;
    }
    return info.getValue();
  },
});

📊 DataTable Component

For a quick and easy table setup, you can use the DataTable component:

import { DataTable } from '@svipulc/custom-ts-table';
import { createColumnHelper } from '@svipulc/custom-ts-table/core/columns';

interface User {
  id: number;
  name: string;
  email: string;
}

const Example = () => {
  const columnHelper = createColumnHelper<User>();

  const columns = [
    columnHelper.accessor('id', {
      header: 'ID',
    }),
    columnHelper.accessor('name', {
      header: 'Name',
    }),
    columnHelper.accessor('email', {
      header: 'Email',
    }),
  ];

  return (
    <DataTable
      data={users}
      columns={columns}
      pagination={true}
      pageSize={10}
      sorting={true}
      globalFilter={true}
      columnsFilter={{
        name: '',
        email: '',
      }}
    />
  );
};

DataTable Props

interface DataTableProps<T> {
  // Required props
  data: T[]; // Data to display
  columns: Column<T>[]; // Column definitions

  // Optional props
  pagination?: boolean; // Enable/disable pagination
  pageSize?: number; // Items per page
  sorting?: boolean; // Enable/disable sorting
  pageIndex?: number; // Initial page index
  globalFilter?: boolean; // Enable/disable global search
  columnsFilter?: FilterCriteria<T>; // Column-specific filters
  className?: string; // Additional CSS classes
}

🤝 Contributing

We welcome contributions to Custom Table! If you have suggestions for improvements or encounter any issues, please feel free to open an issue or submit a pull request on our GitHub repository.

📝 License

Custom Table is MIT licensed. See the LICENSE file for details.

🙏 Acknowledgments

  • Inspired by TanStack Table
  • Built with TypeScript and React

🐛 Bug Reports

If you encounter any bugs or issues, please report them on our GitHub Issues page.

🔮 Future Plans

We're constantly working to improve Custom Table. Here are some features we're planning to add in the future:

  • Column resizing
  • Row selection
  • Expandable rows
  • CSV/Excel export

Stay tuned for updates!


Made with ❤️ by vipul chandravadiya