Skip to content

A reactive notebook for Python — run reproducible experiments, query with SQL, execute as a script, deploy as an app, and version with git. Stored as pure Python. All in a modern, AI-native editor.

Support sticky headers on table (#6486)

Florian Verdoncke41ee819e830
diff --git a/examples/ui/table.py b/examples/ui/table.py
index 60659146f8..bc470d3636 100644
--- a/examples/ui/table.py
+++ b/examples/ui/table.py
@@ -37,6 +37,19 @@ def _(table):
table.value
return
+def _(mo):
+ # Demonstrate a long table with a sticky header and a custom max height
+ long_rows = [{"row": i, "first_name": f"First {i}", "last_name": f"Last {i}"} for i in range(200)]
+ long_table = mo.ui.table(
+ long_rows,
+ pagination=False,
+ max_height=300,
+ )
+ long_table
+ return (long_table,)
+
+
if __name__ == "__main__":
app.run()
diff --git a/frontend/src/components/data-table/data-table.tsx b/frontend/src/components/data-table/data-table.tsx
index 01038eaa16..5e7dd0740c 100644
--- a/frontend/src/components/data-table/data-table.tsx
+++ b/frontend/src/components/data-table/data-table.tsx
@@ -47,6 +47,7 @@ import { getStableRowId } from "./utils";
interface DataTableProps<TData> extends Partial<DownloadActionProps> {
wrapperClassName?: string;
className?: string;
+ maxHeight?: number;
columns: Array<ColumnDef<TData>>;
data: TData[];
// Sorting
@@ -95,6 +96,7 @@ interface DataTableProps<TData> extends Partial<DownloadActionProps> {
const DataTableInternal = <TData,>({
wrapperClassName,
className,
+ maxHeight,
columns,
data,
selection,
@@ -250,6 +252,32 @@ const DataTableInternal = <TData,>({
const rowViewerPanelOpen = isPanelOpen?.("row-viewer") ?? false;
+ const tableRef = React.useRef<HTMLTableElement | null>(null);
+
+ // Why use a ref to set max-height on the wrapper?
+ // - position: sticky only works when the sticky element's nearest scrollable
+ // ancestor is its immediate container. If max-height/overflow are applied
+ // on a grandparent, sticky table headers (th) will not stick.
+ // - We keep the scroll wrapper colocated with the base Table component, but
+ // derive the scroll boundary from maxHeight here to avoid coupling UI base
+ // components to data-table specifics or expanding their API surface.
+ // - Setting styles on the table's direct wrapper ensures the header sticks
+ // reliably across browsers without changing upstream components.
+ React.useEffect(() => {
+ if (!tableRef.current) return;
+ const wrapper = tableRef.current.parentElement as HTMLDivElement | null;
+ if (!wrapper) return;
+ if (maxHeight) {
+ wrapper.style.maxHeight = `${maxHeight}px`;
+ // Ensure wrapper scrolls
+ if (!wrapper.style.overflow) {
+ wrapper.style.overflow = "auto";
+ }
+ } else {
+ wrapper.style.removeProperty("max-height");
+ }
+ }, [maxHeight]);
+
return (
<div className={cn(wrapperClassName, "flex flex-col space-y-1")}>
<FilterPills filters={filters} table={table} />
@@ -263,11 +291,11 @@ const DataTableInternal = <TData,>({
reloading={reloading}
/>
)}
- <Table className="relative">
+ <Table className="relative" ref={tableRef}>
{showLoadingBar && (
<div className="absolute top-0 left-0 h-[3px] w-1/2 bg-primary animate-slide" />
)}
- {renderTableHeader(table)}
+ {renderTableHeader(table, Boolean(maxHeight))}
<CellSelectionProvider>
<DataTableBody
table={table}
diff --git a/frontend/src/components/data-table/renderers.tsx b/frontend/src/components/data-table/renderers.tsx
index 7bb2062391..55e979b6a8 100644
--- a/frontend/src/components/data-table/renderers.tsx
+++ b/frontend/src/components/data-table/renderers.tsx
@@ -26,6 +26,7 @@ import { useScrollIntoViewOnFocus } from "./range-focus/use-scroll-into-view";
export function renderTableHeader<TData>(
table: Table<TData>,
+ isSticky?: boolean,
): JSX.Element | null {
if (!table.getRowModel().rows?.length) {
return null;
@@ -57,7 +58,7 @@ export function renderTableHeader<TData>(
};
return (
- <TableHeader>
+ <TableHeader className={cn(isSticky && "sticky top-0 z-10")}>
<TableRow>
{renderHeaderGroup(table.getLeftHeaderGroups())}
{renderHeaderGroup(table.getCenterHeaderGroups())}
diff --git a/frontend/src/plugins/impl/DataTablePlugin.tsx b/frontend/src/plugins/impl/DataTablePlugin.tsx
index 4381498dfb..a3ffc6fd68 100644
--- a/frontend/src/plugins/impl/DataTablePlugin.tsx
+++ b/frontend/src/plugins/impl/DataTablePlugin.tsx
@@ -172,6 +172,7 @@ interface Data<T> {
totalRows: number | TooManyRows;
pagination: boolean;
pageSize: number;
+ maxHeight?: number;
selection: DataTableSelection;
showDownload: boolean;
showFilters: boolean;
@@ -259,6 +260,7 @@ export const DataTablePlugin = createPlugin<S>("marimo-table")
totalColumns: z.number(),
maxColumns: z.union([z.number(), z.literal("all")]).default("all"),
hasStableRowId: z.boolean().default(false),
+ maxHeight: z.number().optional(),
cellStyles: z.record(z.record(z.object({}).passthrough())).optional(),
hoverTemplate: z.string().optional(),
// Whether to load the data lazily.
@@ -653,6 +655,7 @@ export const LoadingDataTableComponent = memo(
toggleDisplayHeader={toggleDisplayHeader}
getRow={getRow}
cellId={cellId}
+ maxHeight={props.maxHeight}
/>
);
@@ -720,6 +723,7 @@ const DataTableComponent = ({
preview_column,
getRow,
cellId,
+ maxHeight,
}: DataTableProps<unknown> &
DataTableSearchProps & {
data: unknown[];
@@ -901,6 +905,7 @@ const DataTableComponent = ({
data={data}
columns={columns}
className={className}
+ maxHeight={maxHeight}
sorting={sorting}
totalRows={totalRows}
totalColumns={totalColumns}
diff --git a/marimo/_plugins/ui/_impl/table.py b/marimo/_plugins/ui/_impl/table.py
index 3a478e0c43..ed375287e7 100644
--- a/marimo/_plugins/ui/_impl/table.py
+++ b/marimo/_plugins/ui/_impl/table.py
@@ -340,6 +340,9 @@ class table(
hover_template (str, optional): A template for the hover text of the table.
max_columns (int, optional): Maximum number of columns to display. Defaults to the
configured default_table_max_columns (50 by default). Set to None to show all columns.
+ max_height (int, optional): Maximum height of the table body in pixels. When set,
+ the table becomes vertically scrollable and the header will be made sticky
+ in the UI to remain visible while scrolling. Defaults to None.
label (str, optional): A descriptive name for the table. Defaults to "".
"""
@@ -447,6 +450,7 @@ class table(
] = None,
style_cell: Optional[Callable[[str, str, Any], dict[str, Any]]] = None,
hover_template: Optional[str] = None,
+ max_height: Optional[int] = None,
# The _internal_* arguments are for overriding and unit tests
# table should take the value unconditionally
_internal_column_charts_row_limit: Optional[int] = None,
@@ -679,6 +683,9 @@ class table(
"hover-template": hover_template,
"lazy": _internal_lazy,
"preload": _internal_preload,
+ "max-height": int(max_height)
+ if max_height is not None
+ else None,
},
on_change=on_change,
functions=(
diff --git a/tests/_plugins/ui/_impl/test_table.py b/tests/_plugins/ui/_impl/test_table.py
index 7ff3d45812..dcf6cbcfb1 100644
--- a/tests/_plugins/ui/_impl/test_table.py
+++ b/tests/_plugins/ui/_impl/test_table.py
@@ -1919,6 +1919,18 @@ def test_default_table_max_columns():
assert get_default_table_max_columns() == DEFAULT_MAX_COLUMNS
+def test_table_max_height():
+ table = ui.table(
+ [{"a": i} for i in range(100)], pagination=False, max_height=300
+ )
+ # Backend should expose optional UI hints when max_height is set
+ assert table._component_args["max-height"] == 300
+
+ table_no_height = ui.table([1, 2, 3])
+ # Keys may be absent when not configured
+ assert table_no_height._component_args["max-height"] is None
+
+
def test_calculate_top_k_rows():
table = ui.table({"A": [1, 3, 3, None, None]})
result = table._calculate_top_k_rows(