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 🙏

© 2025 – Pkg Stats / Ryan Hefner

@luix_eduard/datatable

v2.0.14

Published

Datatable v2

Readme

React Datatable (TypeScript)

Componente de tabla basado en DataTables.net para React y TypeScript, que soporta tanto paginación/control “backend” como control “frontend”.


📦 Instalación

`npm i @luix_eduard/datatable`
# o con yarn
yarn add @luix_eduard/datatable

🚀 Uso Básico

Importar el componente

import Datatable from '@luix_eduard/datatable';
import type { DatatableType } from '@luix_eduard/datatable';

Definir tu tipo de dato

interface Producto {
  id: number;
  title: string;
  price: number;
  category: string;
  rating: { rate: number; count: number };
  createdAt: Date;
}

🧩 Props Principales (DatatableType<T>)

El componente exporta dos modos de control:

  1. Backend-controlled (control="back")
  2. Frontend-controlled (control="front")

Ambos comparten las props comunes:

| Prop | Tipo | Descripción | | --------------- | -------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------- | | headers | string[] | Headers[][] | Encabezados de columnas. Puede ser un array plano o matriz para múltiples filas de encabezado. | | footers? | string[] | Headers[][] | Pie de tabla. Igual estructura que headers. | | columns | Column<T>[] | Definición de cada columna (campo, formato, render, etc.). | | columnDef? | ColumnDef[] | Opciones de configuración de DataTables (visibilidad, orden, clase CSS, etc.). | | pagging? | boolean | Mostrar controles de paginación. | | info? | boolean | Mostrar información de registros. | | searching? | boolean | Habilitar búsqueda interna. | | saveState? | boolean | Guardar estado (página, orden, búsqueda) en localStorage. | | lengthMenu? | (number | LengthMenu)[] | Opciones de número de filas por página. | | order? | ([number, 'ASC'|'DESC'|1|-1] | OrderTable)[] | Orden por defecto: índice de columna y dirección. | | multiple_order? | boolean | Permitir múltiples columnas de orden. | | stateRefresh? | [boolean, React.Dispatch<React.SetStateAction<boolean>>] | Forzar refresco manual. |


🎛️ Modo “Backend Controlled”

Uso cuando los datos se obtienen de un servidor paginado:

<Datatable<Producto>
  control="back"
  headers={['Título', 'Categoría', 'Precio', 'Fecha']}
  footers={['Título', 'Categoría', 'Precio', 'Fecha']}
  columns={[
    { fieldName: 'title' },
    { fieldName: 'category' },
    { fieldName: 'price', format: 'currency' },
    { fieldName: 'createdAt', format: 'datetime', formatOptions: { locale: es } },
  ]}
  columnDef={[{ target: 2, classname: 'text-right' }]}
  lengthMenu={[5, 10, 25, { label: 'Todos', value: -1 }]}
  order={[[0, 'ASC']]}
  getData={async (page, records, columns, orderValue, search) => {
    const resp = await fetch(`/api/products?page=${page + 1}&limit=${records}&sort=${orderValue[0][1]}`);
    const { data, pagination } = await resp.json();
    return {
      rows: data.map((p: Producto) => ({ ...p, createdAt: new Date(p.createdAt) })),
      page: pagination.page - 1,
      records: pagination.limit,
      count: pagination.total
    };
  }}
/>
  • getData debe devolver un objeto { rows, page, records, count } de tipo Promise<Data<T>>.

🎛️ Modo “Frontend Controlled”

Uso cuando ya tienes todos los datos cargados en memoria:

const [productos, setProductos] = useState<Producto[]>([]);

<Datatable<Producto>
  control="front"
  headers={['Título', 'Categoría', 'Precio', 'Fecha']}
  columns={[
    { fieldName: 'title' },
    { fieldName: 'category' },
    { fieldName: 'price', format: 'currency' },
    { fieldName: 'createdAt', format: 'datetime', formatOptions: { locale: es } },
  ]}
  data={[productos, setProductos]}  // ó simplemente [productos] si no necesitas modificar
  multiple_order={false}
/>
  • Pasas data como [rows] o [rows, setRows].
  • No se usa getData en este modo.

🔍 Detalle de Tipos Auxiliares

Column<T>

export type Column<T> = {
  fieldName: NestedKey<T> | keyof T | null;
  orderValue?: NestedKey<T> | keyof T | null;
  renderFn?: (data: any) => any;
  format?: FormatType<T>;
  formatOptions?: Intl.NumberFormatOptions | FormatOptions;
}
  • fieldName: Ruta al dato (incluye claves anidadas con ‘.’).
  • orderValue: Campo para orden (por defecto igual a `fieldName`).
  • renderFn: Función de render personalizado.
  • format: Tipo de formato (currency, decimal, percent, unit, date, datetime o función).
  • formatOptions: Opciones de Intl.NumberFormat o date-fns (FormatOptions).

NestedKey<T>

Permite referenciar propiedades anidadas con cadenas tipo "rating.rate".

❓ Preguntas y respuestas

¿Como obtener las propiedades de columna?

type Props = React.ComponentProps<typeof Datatable<User>>;
type ColumnType = Props['columns'];

📄 Licencia

MIT © [luixeduard]