Skip to content

Commit

Permalink
docs: column sizing/resizing guide (#5228)
Browse files Browse the repository at this point in the history
  • Loading branch information
KevinVandy committed Dec 27, 2023
1 parent ae4c451 commit d45b9a9
Show file tree
Hide file tree
Showing 17 changed files with 911 additions and 238 deletions.
140 changes: 138 additions & 2 deletions docs/guide/column-sizing.md
Expand Up @@ -7,15 +7,18 @@ title: Column Sizing
Want to skip to the implementation? Check out these examples:

- [column-sizing](../examples/react/column-sizing)
- [column-resizing-performant](../examples/react/column-resizing-performant)

## API

[Column Sizing API](../api/features/column-sizing)

## Overview
## Guide

The column sizing feature allows you to optionally specify the width of each column including min and max widths. It also allows you and your users the ability to dynamically change the width of all columns at will, eg. by dragging the column headers.

### Column Widths

Columns by default are given the following measurement options:

```tsx
Expand All @@ -28,9 +31,30 @@ export const defaultColumnSizing = {

These defaults can be overridden by both `tableOptions.defaultColumn` and individual column defs, in that order.

```tsx
const columns = [
{
accessorKey: 'col1',
size: 270, //set column size for this column
},
//...
]

const table = useReactTable({
//override default column sizing
defaultColumn: {
size: 200, //starting column size
minSize: 50, //enforced during column resizing
maxSize: 500, //enforced during column resizing
},
})
```

The column "sizes" are stored in the table state as numbers, and are usually interpreted as pixel unit values, but you can hook up these column sizing values to your css styles however you see fit.

As a headless utility, table logic for column sizing is really only a collection of states that you can apply to your own layouts how you see fit (our example above implements 2 styles of this logic). You can apply these width measurements in a variety of ways:

- `table` elements or any elements being displayed in a table css mode
- semantic `table` elements or any elements being displayed in a table css mode
- `div/span` elements or any elements being displayed in a non-table css mode
- Block level elements with strict widths
- Absolutely positioned elements with strict widths
Expand All @@ -39,3 +63,115 @@ As a headless utility, table logic for column sizing is really only a collection
- Really any layout mechanism that can interpolate cell widths into a table structure.

Each of these approaches has its own tradeoffs and limitations which are usually opinions held by a UI/component library or design system, luckily not you 馃槈.

### Column Resizing

TanStack Table provides built-in column resizing state and APIs that allow you to easily implement column resizing in your table UI with a variety of options for UX and performance.

#### Enable Column Resizing

By default, the `column.getCanResize()` API will return `true` by default for all columns, but you can either disable column resizing for all columns with the `enableColumnResizing` table option, or disable column resizing on a per-column basis with the `enableResizing` column option.

```tsx
const columns = [
{
accessorKey: 'id',
enableResizing: false, //disable resizing for just this column
size: 200, //starting column size
},
//...
]
```

#### Column Resize Mode

By default, the column resize mode is set to `"onEnd"`. This means that the `column.getSize()` API will not return the new column size until the user has finished resizing (dragging) the column. Usually a small UI indicator will be displayed while the user is resizing the column.

In React TanStack Table adapter, where achieving 60 fps column resizing renders can be difficult, depending on the complexity of your table or web page, the `"onEnd"` column resize mode can be a good default option to avoid stuttering or lagging while the user resizes columns. That is not to say that you cannot achieve 60 fps column resizing renders while using TanStack React Table, but you may have to do some extra memoization or other performance optimizations in order to achieve this.

> Advanced column resizing performance tips will be discussed [down below](#advancedcolumnresizingperformance).
If you want to change the column resize mode to `"onChange"` for immediate column resizing renders, you can do so with the `columnResizeMode` table option.

```tsx
const table = useReactTable({
//...
columnResizeMode: 'onChange', //change column resize mode to "onChange"
})
```

#### Column Resize Direction

By default, TanStack Table assumes that the table markup is laid out in a left-to-right direction. For right-to-left layouts, you may need to change the column resize direction to `"rtl"`.

```tsx
const table = useReactTable({
//...
columnResizeDirection: 'rtl', //change column resize direction to "rtl" for certain locales
})
```

#### Connect Column Resizing APIs to UI

There are a few really handy APIs that you can use to hook up your column resizing drag interactions to your UI.

##### Column Size APIs

To apply the size of a column to the column head cells, data cells, or footer cells, you can use the following APIs:

```ts
header.getSize()
column.getSize()
cell.column.getSize()
```

How you apply these size styles to your markup is up to you, but it is pretty common to use either CSS variables or inline styles to apply the column sizes.

```tsx
<th
key={header.id}
colSpan={header.colSpan}
style={{ width: `${header.getSize()}px` }}
>
```

Though, as discussed in the [advanced column resizing performance section](#advancedcolumnresizingperformance), you may want to consider using CSS variables to apply column sizes to your markup.

##### Column Resize APIs

TanStack Table provides a pre-built event handler to make your drag interactions easy to implement. These event handlers are just convenience functions that call other internal APIs to update the column sizing state and re-render the table. Use `header.getResizeHandler()` to connect to your column resize drag interactions, for both mouse and touch events.

```tsx
<ColumnResizeHandle
onMouseDown={header.getResizeHandler()} //for desktop
onTouchStart={header.getResizeHandler()} //for mobile
/>
```

##### Column Resize Indicator with ColumnSizingInfoState

TanStack Table keeps track of an state object called `columnSizingInfo` that you can use to render a column resize indicator UI.

```jsx
<ColumnResizeIndicator
style={{
transform: header.column.getIsResizing()
? `translateX(${table.getState().columnSizingInfo.deltaOffset}px)`
: '',
}}
/>
```

#### Advanced Column Resizing Performance

If you are creating large or complex tables (and using React 馃槈), you may find that if you do not add proper memoization to your render logic, your users may experience degraded performance while resizing columns.

We have created a [performant column resizing example](../examples/react/column-resizing-performant) that demonstrates how to achieve 60 fps column resizing renders with a complex table that may otherwise have slow renders. It is recommended that you just look at that example to see how it is done, but these are the basic things to keep in mind:

1. Don't use `column.getSize()` on every header and every data cell. Instead, calculate all column widths once upfront, **memoized**!
2. Memoize your Table Body while resizing is in progress.
3. Use CSS variables to communicate column widths to your table cells.

If you follow these steps, you should see significant performance improvements while resizing columns.

If you are not using React, and are using the Svelte, Vue, or Solid adapters instead, you may not need to worry about this as much, but similar principles apply.
2 changes: 1 addition & 1 deletion docs/guide/row-selection.md
Expand Up @@ -161,7 +161,7 @@ const columns = [
]
```

#### Connect Row Selection to Row Click Events
#### Connect Row Selection APIs to UI

If you want a simpler row selection UI, you can just hook up click events to the row itself. The `row.getToggleSelectedHandler()` API is also useful for this use case.

Expand Down
18 changes: 18 additions & 0 deletions docs/guide/virtualization.md
@@ -0,0 +1,18 @@
---
title: Virtualization
---

## Examples

Want to skip to the implementation? Check out these examples:

- [virtualized-rows](../examples/react/virtualized-rows)
- [virtualized-infinite-scrolling](../examples/react/virtualized-infinite-scrolling)

## API

[TanStack Virtual Virtualizer API](../../../../virtual/v3/docs/api/virtualizer)

## Guide

The TanStack Table packages do not come with any virtualization APIs or features built-in, but TanStack Table can easily work with other virtualization libraries like [react-window](https://www.npmjs.com/package/react-window) or TanStack's own [TanStack Virtual](https://tanstack.com/virtual/v3)
5 changes: 5 additions & 0 deletions examples/react/column-resizing-performant/.gitignore
@@ -0,0 +1,5 @@
node_modules
.DS_Store
dist
dist-ssr
*.local
6 changes: 6 additions & 0 deletions examples/react/column-resizing-performant/README.md
@@ -0,0 +1,6 @@
# Example

To run this example:

- `npm install` or `yarn`
- `npm run start` or `yarn start`
13 changes: 13 additions & 0 deletions examples/react/column-resizing-performant/index.html
@@ -0,0 +1,13 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Vite App</title>
<script type="module" src="https://cdn.skypack.dev/twind/shim"></script>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>
21 changes: 21 additions & 0 deletions examples/react/column-resizing-performant/package.json
@@ -0,0 +1,21 @@
{
"name": "tanstack-table-example-column-resizing-performant",
"version": "0.0.0",
"private": true,
"scripts": {
"dev": "vite",
"build": "vite build",
"serve": "vite preview --port 3001",
"start": "vite"
},
"dependencies": {
"@tanstack/react-table": "8.11.2",
"react": "^18.2.0",
"react-dom": "^18.2.0"
},
"devDependencies": {
"@rollup/plugin-replace": "^5.0.1",
"@vitejs/plugin-react": "^2.2.0",
"vite": "^3.2.3"
}
}
73 changes: 73 additions & 0 deletions examples/react/column-resizing-performant/src/index.css
@@ -0,0 +1,73 @@
* {
box-sizing: border-box;
}

html {
font-family: sans-serif;
font-size: 14px;
}

table,
.divTable {
border: 1px solid lightgray;
width: fit-content;
}

.tr {
display: flex;
}

tr,
.tr {
width: fit-content;
height: 30px;
}

th,
.th,
td,
.td {
box-shadow: inset 0 0 0 1px lightgray;
padding: 0.25rem;
}

th,
.th {
padding: 2px 4px;
position: relative;
font-weight: bold;
text-align: center;
height: 30px;
}

td,
.td {
height: 30px;
}

.resizer {
position: absolute;
top: 0;
height: 100%;
right: 0;
width: 5px;
background: rgba(0, 0, 0, 0.5);
cursor: col-resize;
user-select: none;
touch-action: none;
}

.resizer.isResizing {
background: blue;
opacity: 1;
}

@media (hover: hover) {
.resizer {
opacity: 0;
}

*:hover > .resizer {
opacity: 1;
}
}

0 comments on commit d45b9a9

Please sign in to comment.