Tremor Blocks Documentation

repository·main·Indexed 19 days ago

https://github.com/tremorlabs/tremor-blocks

A Next.js project providing a collection of UI components and blocks bootstrapped with create-next-app. It includes a library of pre-built blocks for account and user management, area charts, badges, and banners, along with utility components like Button, Container, and a comprehensive Icons library. The project features data retrieval functions like getBlocks() and getBlocksMDX() to fetch block metadata and raw MDX content, and a BlocksPreview component for dynamic rendering.

Tokens
303.4K
Snippets
355
Records
394
Agent score
64%

What's inside Tremor Blocks

  1. Implement a column object for DataTableFilter

    main

    The DataTableFilter component requires a column object to manage the state of the filter. This object must adhere to the following interface:

    interface ColumnInterface {
      getFilterValue: () => any;
      setFilterValue: (value: any) => void;
    }

    When a user selects an option in the popover and clicks Apply, setFilterValue is called with the new value. When a user clicks the Reset icon (the RiAddLine icon) or the Reset button, setFilterValue is called with an empty string '' to clear the filter.

    // Example of a manual implementation
    const [status, setStatus] = React.useState<string>('');
    
    const statusColumn = {
      getFilterValue: () => status,
      setFilterValue: (value: string) => setStatus(value),
    };
  2. Handle data interaction with onValueChange

    main

    The onValueChange prop allows you to respond to user interactions with the chart. It can be triggered by clicking a specific data point (dot) or an entire category (via the legend or a hidden line overlay).

    Event Types

    • dot: Triggered when a user clicks a specific point on an area. Returns the full payload of that data point.
    • category: Triggered when a user clicks a category in the legend or the area itself. Returns the categoryClicked name.

    Event Object Shape

    When an event occurs, the callback receives an object with the following structure:

    type AreaChartEventProps = {
      eventType: 'dot' | 'category';
      categoryClicked: string;
      // ... other properties from the data point if eventType is 'dot'
    } | null;
    <AreaChart
      data={data}
      index="date"
      categories={['AUM', 'Revenue']}
      onValueChange={(event) => {
        if (event?.eventType === 'dot') {
          console.log('Clicked point in category:', event.categoryClicked, 'Data:', event);
        } else if (event?.eventType === 'category') {
          console.log('Clicked category:', event.categoryClicked);
        } else {
          console.log('Interaction cleared');
        }
      }}
    />
  3. Configure column alignment via ColumnMeta

    main

    You can extend the @tanstack/react-table ColumnMeta interface to include an align property. This allows you to pass alignment metadata (e.g., 'text-left', 'text-right') directly into your column definitions and apply it to your TableCell or TableHeaderCell components using a utility like cx (classnames).

    // 1. Extend the interface
    declare module '@tanstack/react-table' {
      interface ColumnMeta<TData extends RowData, TValue> {
        align: string;
      }
    }
    
    // 2. Use it in column definitions
    const columns = [
      {
        header: 'Costs',
        accessorKey: 'costs',
        meta: {
          align: 'text-right',
        },
      },
    ];
    
    // 3. Apply it in the component
    <TableCell className={cx(cell.column.columnDef.meta?.align)}>
      {flexRender(cell.column.columnDef.cell, cell.getContext())}
    </TableCell>
  4. Create responsive AreaChart variations

    main

    You can render different versions of an AreaChart based on screen size to optimize for mobile users. A common pattern is to show a full chart with a Y-axis on larger screens and a simplified version (hiding the Y-axis and using startEndOnly) on smaller screens.

    Responsive Pattern

    • Desktop (sm:block): Show the full chart with yAxisWidth and showLegend.
    • Mobile (sm:hidden): Show a simplified chart using showYAxis={false} and startEndOnly={true} to maximize space for the data line.
    {/* Desktop Version */}
    <AreaChart
      data={data}
      index="date"
      categories={['Successful requests', 'Errors']}
      colors={['blue', 'red']}
      showLegend={false}
      yAxisWidth={44}
      valueFormatter={valueFormatter}
      fill="solid"
      className="mt-10 hidden h-72 sm:block"
    />
    
    {/* Mobile Version */}
    <AreaChart
      data={data}
      index="date"
      categories={['Successful requests', 'Errors']}
      colors={['blue', 'red']}
      showLegend={false}
      showYAxis={false}
      startEndOnly={true}
      valueFormatter={valueFormatter}
      fill="solid"
      className="mt-6 h-72 sm:hidden"
    />
  5. Configure Tailwind CSS animations for Tremor Blocks

    main

    To enable the fade-up animation used in several components (like the Plan Configurator example), you must add the following keyframes and animation configuration to your tailwind.config.js file:

    // tailwind.config.js
    module.exports = {
      theme: {
        extend: {
          keyframes: {
            'fade-up': {
              from: {
                opacity: 0,
                transform: 'translateY(16px)',
              },
              to: {
                opacity: 1,
                transform: 'translateY(0px)',
              },
            },
          },
          animation: {
            'fade-up': 'fade-up 800ms cubic-bezier(0.34, 1.56, 0.64, 1)',
          },
        },
      },
    }
    module.exports = {
      theme: {
        extend: {
          keyframes: {
            'fade-up': {
              from: {
                opacity: 0,
                transform: 'translateY(16px)',
              },
              to: {
                opacity: 1,
                transform: 'translateY(0px)',
              },
            },
          },
          animation: {
            'fade-up': 'fade-up 800ms cubic-bezier(0.34, 1.56, 0.64, 1)',
          },
        },
      },
    }
  6. Add custom colors to chartColors definition

    main

    To use custom color names in a BarChart (via the colors prop), you must define them in your chartColors utility (typically found in @/lib/chartUtils). Each color definition requires bg, stroke, fill, and text keys using Tailwind CSS classes.

    Example definition for lightEmerald:

    // Add this to your chartColors definition in utils.ts
    lightEmerald: {
      bg: "bg-emerald-300/50 dark:bg-emerald-800/50",
      stroke: "stroke-emerald-300/50 dark:stroke-emerald-800/50",
      fill: "fill-emerald-300/50 dark:fill-emerald-800/50",
      text: "text-emerald-300/50 dark:text-emerald-800/50",
    },
  7. Implement paginated tables with @tanstack/react-table

    main

    To create a paginated table, use the useReactTable hook from @tanstack/react-table and provide the getPaginationRowModel function. You can control the initial page size and index via the initialState.pagination property.

    Key methods for controlling pagination include:

    • table.previousPage(): Navigates to the previous page.
    • table.nextPage(): Navigates to the next page.
    • table.setPageIndex(index): Jumps to a specific page index.
    • table.getPageCount(): Returns the total number of pages.
    • table.getCanPreviousPage() / table.getCanNextPage(): Boolean checks to disable navigation buttons at boundaries.
    • table.getState().pagination.pageIndex: Accesses the current zero-based page index.
    import { 
      useReactTable, 
      getCoreRowModel, 
      getPaginationRowModel 
    } from '@tanstack/react-table';
    
    const table = useReactTable({
      data: data,
      columns: columns,
      getCoreRowModel: getCoreRowModel(),
      getPaginationRowModel: getPaginationRowModel(),
      initialState: {
        pagination: {
          pageIndex: 0,
          pageSize: 8,
        },
      },
    });
  8. Center the login form on the screen

    main

    To ensure the login form is vertically and horizontally centered on the screen, you must ensure the root HTML and body elements occupy the full height of the viewport.

    Modify your layout or template file to include the h-full class on both the <html> and <body> tags:

    <html className="h-full"/>
    <body className="h-full"/>
    <html className="h-full"/>
    <body className="h-full"/>