Bklit charts in your React DataGrid

By raduยท

View as Markdown
Bklit UI is an open-source (MIT) chart library for React, built on d3 and Motion. It isn't an npm package: like shadcn/ui, it's a registry, and the shadcn CLI copies the source of a chart into your project. Once it's there, it's your code, and you can change anything in it.
A chart that's just a React component in your codebase can go anywhere you render React - including the cells of <InfiniteTable />.
The demo below is a "top pages" view of a website's analytics. Every page has a Bklit sparkline of its daily visitors, every section has one too, and the chart at the top draws the pages you select in the grid. Change the range, select a few more pages, hover the chart.
#
Top pages: Infinite Table with Bklit charts
Select pages with the checkboxes to add them to the chart (the first five get a line) and click a page in the legend to remove it. The sparkline of a page in the chart has the color of its line.
open
loading demoโ€ฆ

Adding Bklit to your project#

In a project set up with shadcn/ui (npx shadcn@latest init), the demo needs two Bklit charts, the line chart and the sparkline:
Terminal
npx shadcn@latest add @bklit/line-chart @bklit/sparkline
npm i @infinite-table/infinite-react
The CLI copies the charts into components/charts and installs what they depend on: d3-shape, d3-scale, d3-array, motion and a few small packages. The demo has the same files in its folder, so it imports them from ./components/charts instead of @/components/charts.

A sparkline in every row#

A column's columns.renderValue can return any React element. The trend column's value is an array of numbers - the visitors of each day in the selected range - and renderValue gives it to an AreaSparkline:
trend: {
  field: 'trend',
  header: 'Trend',
  defaultWidth: 150,
  sortable: false,
  renderValue: ({ value, data, rowInfo, column }) => (
    <AreaSparkline
      data={(value as number[] | undefined) ?? []}
      dataKey={dayValue}
      // the column width, without the cell's padding - also while resizing
      width={column.computedWidth - CELL_PADDING_X}
      height={28}
      // start at 0, so small changes don't look like big ones
      yDomain={[0, undefined]}
      curve="monotone"
      // cells are reused for other rows while scrolling: no morphing between them
      animate={false}
      // the charted pages get the color of their line in the chart
      color={
        rowInfo.isGroupRow
          ? 'var(--foreground)'
          : colors.get(data?.path ?? '') ?? 'var(--muted-foreground)'
      }
      fillOpacity={0.25}
    />
  ),
},
Two of those props are there because of how Infinite Table renders cells:
  • width. By default, a sparkline is as wide as its parent. In a cell, the parent is the cell's content, which is only as wide as what it holds - so there's nothing to fill. The column's computedWidth is the width we want, and it changes while you resize the column, so the sparkline follows.
  • animate={false}. Infinite Table only renders the rows you can see. When you scroll, it keeps its cells and gives them the rows that come into view. A Bklit sparkline animates from its old data to its new data, so with animations on, the sparklines would morph from one row into another while you scroll.

Sparklines for the groups, from an aggregation#

The pages are grouped by section, and group rows use the same trend column. The value they get is the result of an aggregation reducer for the trend field: the visitors of all the pages in the section, summed day by day.
const aggregationReducers: DataSourcePropAggregationReducers<PageRow> = {
  visitors: { field: 'visitors', initialValue: 0, reducer: sum },
  previous: { field: 'previous', initialValue: 0, reducer: sum },
  // the group's daily visitors: the sum of its pages, day by day -
  // so group rows get a sparkline too
  trend: {
    field: 'trend',
    initialValue: () => [] as number[],
    reducer: (acc: number[], trend: number[]) =>
      trend.map((value, day) => value + (acc[day] ?? 0)),
  },
  change: {
    field: 'change',
    initialValue: () => ({ visitors: 0, previous: 0 }),
    getter: (row) => row,
    reducer: (acc: { visitors: number; previous: number }, row: PageRow) => ({
      visitors: acc.visitors + row.visitors,
      previous: acc.previous + row.previous,
    }),
    done: (acc: { visitors: number; previous: number }) =>
      acc.previous ? (acc.visitors - acc.previous) / acc.previous : null,
  },
  bounceRate: { field: 'bounceRate', ...weightedAverage('bounceRate') },
  avgTime: { field: 'avgTime', ...weightedAverage('avgTime') },
};
Infinite Table puts the result of a reducer in the data of the group row, under the reducer's field. So renderValue gets the summed array as its value, and the same code draws the sparkline of a page and the one of its section. The other reducers work the same way: visitors are summed, the change is computed from the section's totals, and the bounce rate and the time on page are averaged, weighted by visitors.

The chart follows the selection#

The grid has multi-row selection with checkboxes, and the selection is controlled: the demo keeps it in its state, so the chart can use it too.
const [rowSelection, setRowSelection] =
  React.useState<DataSourcePropRowSelection_MultiRow>({
    selectedRows: [
      '/docs/learn/getting-started',
      '/pricing',
      '/blog/bklit-charts',
    ],
    defaultSelection: false,
  });

// the selected pages, in the order they were selected (select all: by visitors)
const selectedPages = React.useMemo(() => {
  if (!rowSelection.defaultSelection) {
    return rowSelection.selectedRows as string[];
  }
  const deselected = new Set(rowSelection.deselectedRows);
  return [...rows]
    .sort((a, b) => b.visitors - a.visitors)
    .map((row) => row.path)
    .filter((path) => !deselected.has(path));
}, [rowSelection, rows]);

// the first 5 of them are drawn in the chart, each with its own color
const colors = useSeriesColors(selectedPages.slice(0, SERIES_COLORS.length));
The primaryKey of the rows is the path of the page, so the selection is a list of paths, in the order you selected them. Selecting a section selects its pages, and the checkbox in the header selects them all (then the selection is "all, except the deselected ones" - the defaultSelection: true branch above).
The first five selected pages get a color, and the color goes in two places: the line in the chart, and the sparkline and the dot in the grid. A page keeps its color while it's in the chart, so removing one page doesn't repaint the others.
The chart is a Bklit LineChart. It takes one object per date, with a key for each line, so the demo builds that from the trend arrays of the selected pages:
function VisitorsChart(props: {
  range: Range;
  rowsByPath: Map<string, PageRow>;
  charted: [path: string, color: string][];
}) {
  const { range, rowsByPath, charted } = props;
  // nothing selected: the total of all pages
  const series = charted.length
    ? charted.map(([path, color]) => ({
        label: path,
        color,
        trend: rowsByPath.get(path)?.trend ?? [],
      }))
    : [
        {
          label: 'All pages',
          color: 'var(--foreground)',
          trend: sumTrends([...rowsByPath.values()]),
        },
      ];

  // Bklit charts take one object per date, with a key for each line
  const data = getDates(range).map((date, day) => {
    const point: Record<string, unknown> = { date };
    series.forEach((s, index) => {
      point[`s${index}`] = s.trend[day] ?? 0;
    });
    return point;
  });

  return (
    <LineChart
      data={data}
      aspectRatio=""
      className="h-[200px]"
      margin={{ top: 16, right: 8, bottom: 28, left: 8 }}
    >
      <Grid horizontal />
      {series.map((s, index) => (
        <Line
          key={s.label}
          dataKey={`s${index}`}
          curve={curveMonotoneX}
          stroke={s.color}
          strokeWidth={2}
        />
      ))}
      <XAxis numTicks={6} />
      <ChartTooltip
        rows={(point) =>
          series.map((s, index) => ({
            color: s.color,
            label: s.label,
            value: formatNumber(point[`s${index}`] as number),
          }))
        }
      />
    </LineChart>
  );
}
With nothing selected, the chart shows the total of all pages.

One set of colors for both#

Infinite Table has a shadcn theme: import @infinite-table/infinite-react/theme/shadcn.css and put the infinite-theme-name--shadcn class name on a parent of the grid, and the grid takes its colors from the shadcn/ui CSS variables - --background, --foreground, --border, --muted-foreground and the others. Bklit charts read the same variables for their tooltip, and add a few of their own, like --chart-grid and --chart-label. So the colors of both are defined once:
/**
 * The shadcn/ui tokens - Infinite Table's `shadcn` theme and the Bklit charts both
 * read them - plus the Bklit chart tokens. In your app they are in your global CSS,
 * with `.dark` for the dark mode; here `.infinite-theme-mode--dark` is the docs' dark mode.
 */
const THEME_CSS = `
@theme inline {
  --color-background: var(--background);
  --color-foreground: var(--foreground);
  --color-card: var(--card);
  --color-muted: var(--muted);
  --color-muted-foreground: var(--muted-foreground);
  --color-border: var(--border);
  --color-chart-label: var(--chart-label);
  --color-chart-tooltip-background: var(--chart-tooltip-background);
  --color-chart-tooltip-foreground: var(--chart-tooltip-foreground);
  --color-chart-tooltip-muted: var(--chart-tooltip-muted);
}

:root {
  --background: oklch(1 0 0);
  --foreground: oklch(0.145 0 0);
  --card: oklch(1 0 0);
  --popover: oklch(1 0 0);
  --popover-foreground: oklch(0.145 0 0);
  --primary: oklch(0.205 0 0);
  --primary-foreground: oklch(0.985 0 0);
  --muted: oklch(0.97 0 0);
  --muted-foreground: oklch(0.556 0 0);
  --accent: oklch(0.97 0 0);
  --destructive: oklch(0.577 0.245 27.325);
  --border: oklch(0.922 0 0);
  --input: oklch(0.922 0 0);
  --ring: oklch(0.708 0 0);

  --series-1: oklch(0.585 0.233 277.117);
  --series-2: oklch(0.769 0.188 70.08);
  --series-3: oklch(0.696 0.17 162.48);
  --series-4: oklch(0.645 0.246 16.439);
  --series-5: oklch(0.685 0.169 237.323);

  --chart-line-primary: var(--series-1);
  --chart-positive: oklch(0.596 0.145 163.225);
  --chart-negative: oklch(0.577 0.245 27.325);
  --chart-background: var(--card);
  --chart-foreground: oklch(0.145 0.004 285);
  --chart-foreground-muted: oklch(0.55 0.014 260);
  --chart-crosshair: oklch(0.556 0 0);
  --chart-grid: oklch(0.922 0 0);
  --chart-label: oklch(0.45 0.01 260);
  --chart-tooltip-background: var(--popover);
  --chart-tooltip-foreground: var(--popover-foreground);
  --chart-tooltip-muted: var(--muted-foreground);
  --chart-indicator-color: oklch(0.21 0.006 285);
  --chart-indicator-secondary-color: oklch(0.913 0 0);
}

.dark,
.infinite-theme-mode--dark {
  --background: oklch(0.145 0 0);
  --foreground: oklch(0.985 0 0);
  --card: oklch(0.17 0 0);
  --popover: oklch(0.205 0 0);
  --popover-foreground: oklch(0.985 0 0);
  --primary: oklch(0.922 0 0);
  --primary-foreground: oklch(0.205 0 0);
  --muted: oklch(0.269 0 0);
  --muted-foreground: oklch(0.708 0 0);
  --accent: oklch(0.269 0 0);
  --destructive: oklch(0.704 0.191 22.216);
  --border: oklch(1 0 0 / 10%);
  --input: oklch(1 0 0 / 15%);
  --ring: oklch(0.556 0 0);

  --series-1: oklch(0.673 0.182 276.935);
  --series-2: oklch(0.828 0.189 84.429);
  --series-3: oklch(0.765 0.177 163.223);
  --series-4: oklch(0.712 0.194 13.428);
  --series-5: oklch(0.746 0.16 232.661);

  --chart-positive: oklch(0.765 0.177 163.223);
  --chart-negative: oklch(0.704 0.191 22.216);
  --chart-foreground: oklch(0.45 0 0);
  --chart-foreground-muted: oklch(0.65 0.01 260);
  --chart-crosshair: oklch(0.45 0 0);
  --chart-grid: oklch(0.25 0 0);
  --chart-label: oklch(0.75 0.01 260);
  --chart-indicator-color: oklch(1 0 0);
  --chart-indicator-secondary-color: oklch(0.145 0 0);
}
`;
In your app, this CSS is in your global stylesheet (shadcn/ui and Bklit put their variables there when you add them), and the dark mode is the dark class name of shadcn/ui. The demo adds the colors of the selected pages (--series-1 to --series-5), and uses infinite-theme-mode--dark for the dark mode, as the rest of these docs.

Wrapping up#

Bklit charts are React components in your codebase, and Infinite Table renders React components in its cells. So most of the integration is passing data around: an array of numbers for each sparkline, an aggregation reducer for the groups, the row selection for the chart.
The full code of the demo is in its code tab. To go further: