shad_data_table() renders a data frame as a
shadcn-styled, client-side table with sorting, filtering, paging, and
row selection. Everything runs in the browser: the whole frame is
serialised once, and interaction never round-trips to R unless you ask
for it.
It is an input, not an output. Place it in the UI like any
other bound component and read its state with
input$<id>.
The minimum
library(shiny)
library(shadshiny)
ui <- page_shad(
shad_data_table("tbl", mtcars)
)
server <- function(input, output, session) {
observe(print(input$tbl))
}Column names become headers, row names are dropped, and each column gets a default cell renderer based on its type: numerics are right-aligned and formatted, dates print ISO, logicals become check marks, and factors and characters print as text.
Reading state
input$<id> is a list describing what the user is
looking at:
| Field | Type | Meaning |
|---|---|---|
selected |
character vector | Row keys, in selection order, and persisting across pages. By
default a key is the row’s 1-based index in the data you passed, as a
string – so as.integer(input$tbl$selected) indexes the
frame. Set row_key to use a column instead. |
sort |
list of {column, direction}
|
Active sort keys, outermost first. direction is
"asc" or "desc". |
filter |
list |
global (string) plus one entry per filtered
column. |
page |
integer | Current 1-based page. |
pageSize |
integer | Rows per page. |
server <- function(input, output, session) {
chosen <- reactive({
keys <- input$tbl$selected
if (!length(keys)) mtcars else mtcars[as.integer(keys), , drop = FALSE]
})
output$n <- renderText(sprintf("%d rows selected", nrow(chosen())))
}Because the default key is a row index into the original frame, you never have to reconstruct the client’s sort or filter in R to know which rows the user picked.
Table options
shad_data_table(
"tbl", sales,
selection = "multiple", # "none", "single", or "multiple"
filter = "both", # "none", "global", "columns", or "both"
page_size = 25,
page_sizes = c(10, 25, 50, 100),
column_visibility = TRUE, # a dropdown to show/hide columns
sticky_header = TRUE,
max_height = "32rem",
empty = "Nothing matches that filter."
)With filter = "both" the table gets a search box above
it and a filter input under each header; "global"
and "columns" give you one or the other.
shad_data_table() serialises the whole frame, so it
guards the size for you: over 100,000 cells it warns, and over 1,000,000
it errors. Pre-aggregate or page server-side before you get there.
Columns and formatting
Pass columns – a named list of shad_col()
specs, keyed by column name. Anything you leave out keeps its
default.
shad_data_table(
"tbl", sales,
columns = list(
order = shad_col("Order #", width = "8rem"),
amount = shad_col("Amount", format = shad_fmt_number(2, prefix = "$")),
margin = shad_col("Margin", format = shad_fmt_percent(1)),
date = shad_col("Date", format = shad_fmt_date("%b %d, %Y")),
status = shad_col("Status", format = shad_fmt_badge(
c(paid = "default", pending = "secondary", refunded = "destructive")
)),
notes = shad_col(visible = FALSE)
)
)shad_col() takes header (the first argument
– the displayed label), plus width, align,
sortable, filterable, visible,
html, and one of format or cell.
format and cell are mutually exclusive, and
neither combines with html = TRUE (which passes the
column’s strings through as raw HTML – only do that with values you
generated).
The bundled formatters are:
| Formatter | Renders |
|---|---|
shad_fmt_number(digits, big_mark, prefix, suffix) |
Fixed-decimal number. |
shad_fmt_percent(digits) |
Value × 100 with a % suffix. |
shad_fmt_date(format) |
format()-style date string,
e.g. "%b %d, %Y". |
shad_fmt_badge(map) |
shad_badge() per value; map is value →
variant. |
Formatters keep the raw value as the sort key, so a
$1,200.00 cell still sorts numerically and a
"Mar 03" cell still sorts chronologically.
Custom cells
When a formatter isn’t enough, give the column a cell
function. It is called once per row with the column value and the whole
row, and returns a tag or a string:
shad_col("Owner", cell = function(value, row) {
shad_item(
shad_avatar(src = row$avatar_url, fallback = substr(value, 1, 2)),
shad_p(value)
)
})Cell functions run in R at render time, not on the client – so they cost one call per visible row of the frame you pass, and they cannot see later filter state. Keep them cheap.
Updating from the server
observeEvent(input$refresh, {
update_shad_data_table("tbl", data = fetch_latest())
})update_shad_data_table() replaces the rows and can patch
selected, page, page_size, and
loading. Pass columns alongside
data to re-apply your formatters and cell
functions to the new rows. The client keeps its sort and filter, so a
refresh doesn’t yank the view out from under the user; the column
headers and visibility are fixed at UI-construction time.
Loading state
shad_data_table("tbl", NULL, loading = TRUE)
# later:
update_shad_data_table("tbl", data = result(), loading = FALSE)loading = TRUE renders skeleton rows at the current page
size.
Server-backed paging (experimental)
For a large dataset, keep the constructor empty and let
shad_data_table_server() request one page at a time. The
helper is an experimental protocol layer around the same table anatomy;
it does not choose a database package or construct queries for you.
ui <- page_shad(
shad_data_table(
"orders", data = NULL, selection = "multiple", filter = "both",
page_size = 25, loading = TRUE
)
)
server_rows <- data.frame(
order_id = sprintf("order-%03d", seq_len(100L)),
customer = paste("Customer", seq_len(100L)),
status = rep(c("paid", "pending", "refunded"), length.out = 100L),
amount = seq(12.50, by = 7.25, length.out = 100L),
stringsAsFactors = FALSE
)
server_source <- function(request) {
filtered <- server_rows
global <- trimws(request$filter$global)
if (nzchar(global)) {
hit <- Reduce(`|`, lapply(filtered, function(x) {
grepl(tolower(global), tolower(as.character(x)), fixed = TRUE)
}))
filtered <- filtered[hit, , drop = FALSE]
}
for (column in names(request$filter$columns)) {
needle <- trimws(request$filter$columns[[column]])
if (nzchar(needle) && column %in% names(filtered)) {
keep <- grepl(tolower(needle), tolower(as.character(filtered[[column]])), fixed = TRUE)
filtered <- filtered[keep, , drop = FALSE]
}
}
for (spec in rev(request$sort)) {
filtered <- filtered[order(
filtered[[spec$column]],
decreasing = identical(spec$direction, "desc"), method = "radix"
), , drop = FALSE]
}
total <- nrow(server_rows)
filtered_total <- nrow(filtered)
first <- (request$page - 1L) * request$page_size + 1L
page <- if (first <= filtered_total) {
filtered[seq.int(first, min(first + request$page_size - 1L, filtered_total)), , drop = FALSE]
} else {
filtered[0, , drop = FALSE]
}
list(data = page, total_rows = total, filtered_rows = filtered_total)
}
server <- function(input, output, session) {
shad_data_table_server(
"orders",
source = server_source,
columns = list(
order_id = shad_col("Order"),
amount = shad_col("Amount", format = shad_fmt_number(2, prefix = "$"))
),
row_key = "order_id",
session = session
)
}For a database source, map request sort names through a fixed
allowlist and use bound parameters for global/column filters, page size,
and offset, for example
DBI::dbGetQuery(conn, sql, params = list(global, page_size, offset)).
Never paste request values or unreviewed sort names directly into
SQL.
The request has validated positive page and
page_size values, a sort list of
{column, direction} pairs, and filter values
containing a global string plus named column filters. The browser sends
it, so it is checked before source runs:
page_size is at most max_page_size (1,000
unless you change it), every sort and filter value is a single string,
and no column is sorted twice. When you pass columns, they
are the allowlist: a request may sort or filter only declared columns
that allow it, and other columns in the page still show but offer
neither. A request that fails a check never reaches source.
The source must return a data frame with no more than
page_size rows and non-negative total_rows and
filtered_rows counts. Column formatters and trusted HTML
use the same R serialization as the client-side table. A unique,
non-missing row_key keeps selection stable across pages; a
missing key retains only the constructor’s page-local fallback.
The table switches to server mode when its value first reaches the
server, so a table that renderUI() draws later, or draws
again, is served too. Call shad_data_table_server() once
beside the render, not inside it. Request IDs make stale requests and
responses harmless. Source failures show a fixed safe browser message
and a retry action while the detailed condition is kept to a server
warning. Editing, grouping, pivoting, aggregation, downloads, and
spreadsheet behavior are intentionally outside this first experimental
mode.
When to keep DT
shad_data_table() ships the whole frame to the browser.
That is the right trade for tables up to roughly the tens of thousands
of rows. For a larger dataset, use the experimental server-backed helper
when its intentionally narrow contract fits; keep
DT::datatable() when you need Excel export or the JS
DataTables plugin ecosystem.
See also
-
vignette("charts")for pairing a table with themed plots. -
shad_run_example("07-data-explorer")for a full app using both.