Data Table
Powerful table and datagrids built using the Table component and plain C#.
| Status | Amount | Actions | ||
|---|---|---|---|---|
success | ken99@example.com | $316.00 | ||
success | Abe45@example.com | $242.00 | ||
processing | Monserrat44@example.com | $837.00 | ||
success | Silas22@example.com | $874.00 | ||
failed | carmella@example.com | $721.00 |
Introduction
Every data table or datagrid I've created has been unique. They all behave differently, have specific sorting and filtering requirements, and work with different data sources.
It doesn't make sense to combine all of these variations into a single component. If we do that, we'll lose the flexibility that headless UI provides.
So instead of a data table component, I thought it would be more helpful to provide a guide on how to build your own. We'll start
with the basic <Table /> component and build a complex data table from scratch.
Table of Contents
This guide will show you how to use the <Table /> component and LINQ to build your own custom data table. We'll cover the following topics:
Installation
Add the <Table /> component to your project:
Prerequisites
We are going to build a table to show recent payments. Here's what our data looks like:
public sealed record Payment(string Id, decimal Amount, string Status, string Email);
public static class Payments
{
public static readonly Payment[] Data =
[
new("728ed52f", 100, "pending", "m@example.com"),
new("489e1d42", 125, "processing", "example@gmail.com"),
];
}Project Structure
Start by creating the following file structure:
Components
└── Pages
└── Payments
├── DataTable.razor
├── Payment.cs
└── Payments.razorI'm using a Blazor Web App example here but this works for any other Blazor project.
Payment.cswill contain our data type and sample data.DataTable.razorwill contain our<DataTable />component: the columns, the rows and the table state.Payments.razoris the page where we'll fetch data and render our table.
Set up Table Features
There's no table engine to install. The table state (filter, sort, page, visibility and selection) is a handful of fields, and the rows you render are a LINQ pipeline over your data: filter, then sort, then page.
Basic Table
Let's start by building a basic table.
Column Definitions
Columns are just markup: a <TableHead /> per column in the header and a matching <TableCell /> per
row. Add the columns you want to display.
<DataTable /> component
Next, we'll create a <DataTable /> component to render our table.
<div class="overflow-hidden rounded-md border">
<Table>
<TableHeader>
<TableRow>
<TableHead>Status</TableHead>
<TableHead>Email</TableHead>
<TableHead>Amount</TableHead>
</TableRow>
</TableHeader>
<TableBody>
@if (Data.Count > 0)
{
@foreach (var payment in Data)
{
<TableRow @key="payment.Id">
<TableCell>@payment.Status</TableCell>
<TableCell>@payment.Email</TableCell>
<TableCell>@payment.Amount</TableCell>
</TableRow>
}
}
else
{
<TableRow>
<TableCell colspan="3" Class="h-24 text-center">No results.</TableCell>
</TableRow>
}
</TableBody>
</Table>
</div>
@code {
[Parameter, EditorRequired] public IReadOnlyList<Payment> Data { get; set; } = [];
}Render the table
Finally, we'll render our table in our page component. Fetch the data in OnInitializedAsync; this example reads Payments.Data, but you'd call your API there.
@page "/payments"
<div class="container mx-auto py-10">
<DataTable Data="@_data" />
</div>
@code {
private IReadOnlyList<Payment> _data = [];
protected override async Task OnInitializedAsync()
{
_data = await Task.FromResult(Payments.Data);
}
}Cell Formatting
Let's format the amount cell to display the dollar amount. We'll also align the cell to the right.
Update the amount header and cell
Format the amount with ToString("C", culture) and right-align the header and the cell.
<TableHead><div class="text-right">Amount</div></TableHead>
...
<TableCell>
<div class="text-right font-medium">@payment.Amount.ToString("C", UsCulture)</div>
</TableCell>
@code {
private static readonly CultureInfo UsCulture = CultureInfo.GetCultureInfo("en-US");
}You can use the same approach to format other cells and headers.
Row Actions
Let's add row actions to our table. We'll use a <DropdownMenu /> component for this.
Add the actions column
@inject IJSRuntime JsRuntime
<TableHead />
...
<TableCell>
<DropdownMenu>
<DropdownMenuTrigger Variant="ButtonVariant.Ghost" Size="ButtonSize.IconXs">
<span class="sr-only">Open menu</span>
<svg>...</svg>
</DropdownMenuTrigger>
<DropdownMenuContent Align="Align.End">
<DropdownMenuGroup>
<DropdownMenuLabel>Actions</DropdownMenuLabel>
<DropdownMenuItem OnClick="@(() => BrowserClipboard.CopyAsync(JsRuntime, payment.Id))">
Copy payment ID
</DropdownMenuItem>
</DropdownMenuGroup>
<DropdownMenuSeparator />
<DropdownMenuGroup>
<DropdownMenuItem>View customer</DropdownMenuItem>
<DropdownMenuItem>View payment details</DropdownMenuItem>
</DropdownMenuGroup>
</DropdownMenuContent>
</DropdownMenu>
</TableCell>
You can access the row data inside the cell markup, since it's rendered in the @foreach loop. Use this to handle actions
for your row, e.g. use the Id to make a request to your API.
Pagination
Next, we'll add pagination to our table.
Page the rows
Keep the page index in a field and take one page of rows. This will paginate your rows into pages of 10.
@foreach (var payment in PageRows)
{
...
}
@code {
private const int PageSize = 10;
private int _pageIndex;
private List<Payment> PageRows => [.. Data.Skip(_pageIndex * PageSize).Take(PageSize)];
private int PageCount => (int)Math.Ceiling(Data.Count / (double)PageSize);
private bool CanPreviousPage => _pageIndex > 0;
private bool CanNextPage => _pageIndex < PageCount - 1;
}Add pagination controls
We can add pagination controls to our table using the <Button /> component.
<div>
<div class="overflow-hidden rounded-md border">
<Table>
...
</Table>
</div>
<div class="flex items-center justify-end space-x-2 py-4">
<Button Variant="ButtonVariant.Outline" Size="ButtonSize.Sm" @onclick="() => _pageIndex--" Disabled="@(!CanPreviousPage)">
Previous
</Button>
<Button Variant="ButtonVariant.Outline" Size="ButtonSize.Sm" @onclick="() => _pageIndex++" Disabled="@(!CanNextPage)">
Next
</Button>
</div>
</div>See Reusable Components section for a more advanced pagination component.
Sorting
Let's make the email column sortable.
Sort the rows
Keep the sort direction in a nullable bool: null is unsorted, false ascending and true descending. Sort the rows by it before taking a page.
@code {
private bool? _emailSortDescending;
private List<Payment> SortedRows => _emailSortDescending switch
{
false => [.. Data.OrderBy(row => row.Email, StringComparer.OrdinalIgnoreCase)],
true => [.. Data.OrderByDescending(row => row.Email, StringComparer.OrdinalIgnoreCase)],
null => [.. Data],
};
private List<Payment> PageRows => [.. SortedRows.Skip(_pageIndex * PageSize).Take(PageSize)];
private void ToggleEmailSorting()
{
_emailSortDescending = _emailSortDescending == false;
_pageIndex = 0;
}
}Make header cell sortable
We can now update the email header cell to add sorting controls.
<TableHead>
<Button Variant="ButtonVariant.Ghost" @onclick="ToggleEmailSorting">
Email
<svg>...</svg>
</Button>
</TableHead>This will automatically sort the table (asc and desc) when the user toggles on the header cell.
Filtering
Let's add a search input to filter emails in our table.
Filter the rows
Filter the rows by the search text, then sort the filtered rows instead of all of them.
@code {
private string? _emailFilter;
private List<Payment> FilteredRows =>
[.. Data.Where(row => string.IsNullOrEmpty(_emailFilter) || row.Email.Contains(_emailFilter, StringComparison.OrdinalIgnoreCase))];
private List<Payment> SortedRows => _emailSortDescending switch
{
false => [.. FilteredRows.OrderBy(row => row.Email, StringComparer.OrdinalIgnoreCase)],
true => [.. FilteredRows.OrderByDescending(row => row.Email, StringComparer.OrdinalIgnoreCase)],
null => FilteredRows,
};
private int PageCount => (int)Math.Ceiling(FilteredRows.Count / (double)PageSize);
private void FilterEmails(string? value)
{
_emailFilter = value;
_pageIndex = 0;
}
}Add the filter input
<div>
<div class="flex items-center py-4">
<Input placeholder="Filter emails..." Value="@_emailFilter" ValueChanged="FilterEmails" Class="max-w-sm" />
</div>
<div class="overflow-hidden rounded-md border">
<Table>
...
</Table>
</div>
</div>Filtering is now enabled for the email column. You can add filters to other columns as well.
Visibility
Adding column visibility is fairly simple using a set of hidden column ids.
Track hidden columns
@code {
private static readonly string[] HideableColumns = ["status", "email", "amount"];
private readonly HashSet<string> _hiddenColumns = [];
private bool IsVisible(string column) => !_hiddenColumns.Contains(column);
private void SetVisible(string column, bool visible)
{
if (visible)
{
_hiddenColumns.Remove(column);
}
else
{
_hiddenColumns.Add(column);
}
}
}Add the column toggle
Render a checkbox item per hideable column, and wrap each column's header and cell in @if (IsVisible("status")).
<div class="flex items-center py-4">
<Input placeholder="Filter emails..." Value="@_emailFilter" ValueChanged="FilterEmails" Class="max-w-sm" />
<DropdownMenu>
<DropdownMenuTrigger Variant="ButtonVariant.Outline" Class="ml-auto">Columns</DropdownMenuTrigger>
<DropdownMenuContent Align="Align.End">
<DropdownMenuGroup>
@foreach (var column in HideableColumns)
{
<DropdownMenuCheckboxItem @key="column" Class="capitalize" Checked="@IsVisible(column)"
CheckedChanged="@(value => SetVisible(column, value))">
@column
</DropdownMenuCheckboxItem>
}
</DropdownMenuGroup>
</DropdownMenuContent>
</DropdownMenu>
</div>
...
@if (IsVisible("status"))
{
<TableCell><div class="capitalize">@payment.Status</div></TableCell>
}This adds a dropdown menu that you can use to toggle column visibility.
Row Selection
Next, we're going to add row selection to our table.
Track selected rows
@code {
private readonly HashSet<string> _rowSelection = [];
private bool AllPageRowsSelected => PageRows.Count > 0 && PageRows.All(row => _rowSelection.Contains(row.Id));
private bool SomePageRowsSelected => PageRows.Any(row => _rowSelection.Contains(row.Id));
private void ToggleSelected(Payment payment, bool selected)
{
if (selected)
{
_rowSelection.Add(payment.Id);
}
else
{
_rowSelection.Remove(payment.Id);
}
}
private void ToggleAllPageRowsSelected(bool selected)
{
foreach (var payment in PageRows)
{
ToggleSelected(payment, selected);
}
}
}Add the select column
<TableHead>
<Checkbox Checked="@AllPageRowsSelected" Indeterminate="@(SomePageRowsSelected && !AllPageRowsSelected)"
CheckedChanged="ToggleAllPageRowsSelected" aria-label="Select all" />
</TableHead>
...
@foreach (var payment in PageRows)
{
var selected = _rowSelection.Contains(payment.Id);
<TableRow @key="payment.Id" data-state="@(selected ? "selected" : null)">
<TableCell>
<Checkbox Checked="@selected" CheckedChanged="@(value => ToggleSelected(payment, value))" aria-label="Select row" />
</TableCell>
...
</TableRow>
}Show selected rows
You can show the number of selected rows using the selection set and the filtered rows.
<div class="flex-1 text-sm text-muted-foreground">
@(FilteredRows.Count(row => _rowSelection.Contains(row.Id))) of @FilteredRows.Count row(s) selected.
</div>Reusable Components
Here are some components you can use to build your data tables.
Column header
Make any column header sortable and hideable. Sorted is null when the column is unsorted, false when it's ascending and true when it's descending; show an arrow-up, arrow-down or chevrons-up-down icon in the trigger to match.
@if (!CanSort)
{
<div class="@Class">@Title</div>
}
else
{
<div class="@Cn("flex items-center gap-2", Class)">
<DropdownMenu>
<DropdownMenuTrigger Variant="ButtonVariant.Ghost" Size="ButtonSize.Sm" Class="-ml-3 h-8 data-popup-open:bg-accent">
<span>@Title</span>
<svg>...</svg>
</DropdownMenuTrigger>
<DropdownMenuContent Align="Align.Start">
<DropdownMenuGroup>
<DropdownMenuItem OnClick="@(() => SortedChanged.InvokeAsync(false))">Asc</DropdownMenuItem>
<DropdownMenuItem OnClick="@(() => SortedChanged.InvokeAsync(true))">Desc</DropdownMenuItem>
</DropdownMenuGroup>
<DropdownMenuSeparator />
<DropdownMenuGroup>
<DropdownMenuItem OnClick="OnHide">Hide</DropdownMenuItem>
</DropdownMenuGroup>
</DropdownMenuContent>
</DropdownMenu>
</div>
}
@code {
[Parameter, EditorRequired] public string Title { get; set; } = "";
[Parameter] public bool CanSort { get; set; } = true;
[Parameter] public bool? Sorted { get; set; }
[Parameter] public EventCallback<bool?> SortedChanged { get; set; }
[Parameter] public EventCallback OnHide { get; set; }
[Parameter] public string? Class { get; set; }
}<TableHead>
<DataTableColumnHeader Title="Email" @bind-Sorted="_emailSortDescending" OnHide="@(() => SetVisible("email", false))" />
</TableHead>Pagination
Add pagination controls to your table including page size and selection count.
<div class="flex items-center justify-between px-2">
<div class="flex-1 text-sm text-muted-foreground">
@SelectedCount of @RowCount row(s) selected.
</div>
<div class="flex items-center space-x-6 lg:space-x-8">
<div class="flex items-center space-x-2">
<p class="text-sm font-medium">Rows per page</p>
<Select Value="@PageSize.ToString(CultureInfo.InvariantCulture)" ValueChanged="SetPageSize" Items="@PageSizes">
<SelectTrigger Class="h-8 w-[70px]"><SelectValue /></SelectTrigger>
<SelectContent Side="Side.Top">
<SelectGroup>
@foreach (var size in PageSizes)
{
<SelectItem @key="size.Value" Value="@size.Value">@size.Label</SelectItem>
}
</SelectGroup>
</SelectContent>
</Select>
</div>
<div class="flex w-[100px] items-center justify-center text-sm font-medium">
Page @(PageIndex + 1) of @PageCount
</div>
<div class="flex items-center space-x-2">
<Button Variant="ButtonVariant.Outline" Size="ButtonSize.Icon" Class="hidden size-8 lg:flex"
@onclick="() => PageIndexChanged.InvokeAsync(0)" Disabled="@(PageIndex == 0)">
<span class="sr-only">Go to first page</span>
<svg>...</svg>
</Button>
<Button Variant="ButtonVariant.Outline" Size="ButtonSize.Icon" Class="size-8"
@onclick="() => PageIndexChanged.InvokeAsync(PageIndex - 1)" Disabled="@(PageIndex == 0)">
<span class="sr-only">Go to previous page</span>
<svg>...</svg>
</Button>
<Button Variant="ButtonVariant.Outline" Size="ButtonSize.Icon" Class="size-8"
@onclick="() => PageIndexChanged.InvokeAsync(PageIndex + 1)" Disabled="@(PageIndex >= PageCount - 1)">
<span class="sr-only">Go to next page</span>
<svg>...</svg>
</Button>
<Button Variant="ButtonVariant.Outline" Size="ButtonSize.Icon" Class="hidden size-8 lg:flex"
@onclick="() => PageIndexChanged.InvokeAsync(PageCount - 1)" Disabled="@(PageIndex >= PageCount - 1)">
<span class="sr-only">Go to last page</span>
<svg>...</svg>
</Button>
</div>
</div>
</div>
@code {
private static readonly SelectOption[] PageSizes =
[.. new[] { 10, 20, 25, 30, 40, 50 }.Select(size => new SelectOption($"{size}", $"{size}"))];
[Parameter] public int PageIndex { get; set; }
[Parameter] public EventCallback<int> PageIndexChanged { get; set; }
[Parameter] public int PageSize { get; set; } = 10;
[Parameter] public EventCallback<int> PageSizeChanged { get; set; }
[Parameter] public int RowCount { get; set; }
[Parameter] public int SelectedCount { get; set; }
private int PageCount => Math.Max(1, (int)Math.Ceiling(RowCount / (double)PageSize));
private async Task SetPageSize(string? value)
{
await PageSizeChanged.InvokeAsync(int.Parse(value!, CultureInfo.InvariantCulture));
await PageIndexChanged.InvokeAsync(0);
}
}<DataTablePagination @bind-PageIndex="_pageIndex" @bind-PageSize="_pageSize"
RowCount="@FilteredRows.Count" SelectedCount="@FilteredRows.Count(row => _rowSelection.Contains(row.Id))" />Column toggle
A component to toggle column visibility.
<DropdownMenu>
<DropdownMenuTrigger Variant="ButtonVariant.Outline" Size="ButtonSize.Sm" Class="ml-auto hidden h-8 lg:flex">
<svg>...</svg>
View
</DropdownMenuTrigger>
<DropdownMenuContent Align="Align.End" Class="w-[150px]">
<DropdownMenuGroup>
<DropdownMenuLabel>Toggle columns</DropdownMenuLabel>
</DropdownMenuGroup>
<DropdownMenuSeparator />
<DropdownMenuGroup>
@foreach (var column in Columns)
{
<DropdownMenuCheckboxItem @key="column" Class="capitalize" Checked="@(!HiddenColumns.Contains(column))"
CheckedChanged="@(visible => Toggle(column, visible))">
@column
</DropdownMenuCheckboxItem>
}
</DropdownMenuGroup>
</DropdownMenuContent>
</DropdownMenu>
@code {
[Parameter, EditorRequired] public IReadOnlyList<string> Columns { get; set; } = [];
[Parameter, EditorRequired] public ISet<string> HiddenColumns { get; set; } = new HashSet<string>();
[Parameter] public EventCallback HiddenColumnsChanged { get; set; }
private Task Toggle(string column, bool visible)
{
if (visible)
{
HiddenColumns.Remove(column);
}
else
{
HiddenColumns.Add(column);
}
return HiddenColumnsChanged.InvokeAsync();
}
}<DataTableViewOptions Columns="@HideableColumns" HiddenColumns="@_hiddenColumns" />RTL
To enable RTL support in Blazix, see the RTL configuration guide.
Translated with AI for the demo, so it may have mistakes.
| الحالة | المبلغ | الإجراءات | ||
|---|---|---|---|---|
ناجح | ken99@example.com | $316.00 | ||
ناجح | Abe45@example.com | $242.00 | ||
قيد المعالجة | Monserrat44@example.com | $837.00 | ||
ناجح | Silas22@example.com | $874.00 | ||
فشل | carmella@example.com | $721.00 |