@sheetxl/grid-react
v1.0.7
Published
Grid React - Advanced grid component for React
Readme
Grid React
A high-performance, virtualized grid component built for React. Part of the SheetXL ecosystem.
Quick Start
Create a grid with just a few lines:
import { Grid } from '@sheetxl/grid-react';
<Grid
rowCount={1000}
columnCount={100}
getRowHeight={24} // a number = uniform size (or a (index) => number)
getColumnWidth={100}
showGridLines
renderCells={(props) => (
<div key={props.key} style={props.style}>
{props.value}
</div>
)}
/>That's it — a virtualized grid that efficiently handles trillions of cells.
renderCells receives a CellRendererProps: { cell, range, bounds, value, style, pane } (plus a
key). style is already positioned/sized for the cell — spread it onto your element. By default a
rendered cell is pointer-events: none so clicks fall through to the grid. To make part of a cell
interactive — a checkbox, a button, a slider — spread CELL_INTERACTIVE_PROPS onto that element and
add its handlers as on any element: a plain press on it selects the cell, starts no drag-select, and
then reaches the element's own onPointerDown; a drag captures the pointer on the element itself.
Why another grid?
Most data grids are configuration-driven. You describe the grid through a large surface of column definitions, feature flags, and renderer callbacks; selection, editing, grouping, notes are each a built-in property you switch on. Anything the library didn't anticipate means bending its plugin API or forking it.
Grid-React starts from a different premise. A grid is a virtualized coordinate space, and everything placed in it — cells, selections, highlights, notes, widgets — is an ordinary React component positioned along the grid's metrics. There's no master list of properties to learn or outgrow: you compose the features you need from small, single-purpose pieces, and your own components sit right next to the built-in ones.
The payoff is a small core with an open surface. The grid owns the genuinely hard parts — virtualization, scroll, zoom, freeze panes, device-pixel alignment — and stays out of the way of what you draw. The mechanism that makes this work is a pair of primitives, below.
The whole model: two primitives
Everything in the grid — the built-in cells, gridlines, and selection included — is built from two primitives, and only two:
A
VirtualDivis a div. Everything you know about divs applies — pointer events, focus, refs, CSS, children. The grid adds exactly one thing: its bounds are driven by the grid metrics. Place it at arange(cell coordinates) orbounds(pixels), and scroll, zoom, freeze panes, device-pixel alignment, and off-screen culling are handled for you.A
Layeris an invisible, view-sized div — the boundary of one z-slot. It never paints and is never a hit target; what it contributes is containment: everything you host inside it — VirtualDivs, plain elements, third-party widgets — belongs to its slot, and the slot orders both painting and event dispatch. Its own handlers are the slot's tap: the outermost handlers of its subtree, and grid-wide ears at its slot on every other layer's turn.
If you can hold those two sentences, you can reason out the whole system. Everything else in this package is a convenience composed from them.
import { Grid, Layer, VirtualDiv, RangeRect } from '@sheetxl/grid-react';
<Grid
rowCount={1000}
columnCount={100}
getRowHeight={24}
getColumnWidth={100}
showGridLines
renderCells={renderCell}
>
{/* a layer of decorations + a widget, above the cells */}
<Layer zIndex={1}>
<RangeRect range={{ colStart: 2, rowStart: 2, colEnd: 5, rowEnd: 6 }}
stroke="#1976d2" alignWidth={2} />
<VirtualDiv range={{ colStart: 6, rowStart: 2, colEnd: 9, rowEnd: 5 }}
style={{ border: '2px solid #1976d2' }}>
A note
</VirtualDiv>
</Layer>
</Grid>Each piece is just a React element with full access to hooks, state, and context — placement, virtualization, freeze-pane clipping, and event routing all "just work."
- Declarative — composed as
children, like any React tree. - Automatic virtualization — only visible content renders; off-screen VirtualDivs cull.
- Freeze panes built-in — correct clipping and coordinate conversion by default.
- Flexible — mix the built-in pieces with your own.
Grid vs GridSurface
There are two entry points:
Grid— batteries-included (what most apps use). It adds cells (renderCells), gridlines (showGridLines), and a content cache to the engine below. Layout convenience lives here:getRowHeight/getColumnWidth(a number, or(index) => number).GridSurface— the pure engine. It knows nothing about cells or gridlines; you compose everything from the primitives (Gridis a thin wrapper that does exactly that). Use it directly when you want full control. It is metrics-only — pass anIGridMetrics(nogetRowHeight).
Both take their layers as children. Grid additionally takes renderBelow (content under
the cells) and renderBorders.
The grid's children are its stack of Layers, bottom → top — like the layers panel of a design
tool (Photoshop, Figma): a layer spans the whole canvas; the objects on it (VirtualDivs) have
positions. This is a closed contract, both ways: a grid's children can only be Layers, and a
Layer can only appear there — never nested inside another Layer or a VirtualDiv
(dev-enforced). A composite feature (a selection, an editor, a table overlay) is a component that
renders exactly one Layer at its root. The stack is therefore always flat: one list, one
order, one place to reason about z.
VirtualDiv — a div, placed by the grid
A <div> whose bounds are driven by the grid metrics. All standard div props work (className,
style, onClick, onPointerDown, tabIndex, ref, …) and mean what they always mean.
<VirtualDiv range={{ colStart: 5, rowStart: 10, colEnd: 8, rowEnd: 15 }} /> // cell coordinates
<VirtualDiv bounds={{ x: 500, y: 1000, width: 200, height: 100 }} /> // grid-space pixels
<VirtualDiv fill /> // the whole viewPlacement is exactly one of:
range— cell coordinates, resolved via the current pane. Culls when off-screen.bounds— CSS pixels from the grid origin. Culls when off-screen.fill— sized to the view, never culled. For full-view content: a background wash, a canvas host, a pointer-capture surface, a container that needs real CSS (overflow,opacity,filter) applied to a whole group.
Under the hood it is a single transform-placed div — no wrappers, no per-instance overhead — with its edges snapped to the device-pixel grid so content stays crisp and adjacent boxes share seam-free boundaries.
Useful extras:
coverGridlines— extend the box by 1 device px so it covers its gridline pixels (like a cell fill).alignWidth— render an aligned border (instead of a fill) that lines up with the selection rectangle.clipInsets— keep the box mounted N px past the viewport edge (for borders/shadows that overhang).keepMounted— stay mounted (parked off-screen) instead of culling when scrolled away (e.g. an editor whose input must never unmount).
A decoration is not a separate concept — it's a VirtualDiv you set pointer-events: none on,
exactly as you would any div:
{/* a highlight: never a hit target, clicks fall through to the grid */}
<VirtualDiv range={range} coverGridlines
style={{ pointerEvents: 'none', background: 'rgba(255,235,59,0.4)' }} />Huge ranges: a VirtualDiv sized to a whole column/row would be millions of pixels tall — a giant compositing layer. For outlines/fills over arbitrary ranges use
RangeRect, which internally keeps its box view-sized and draws the shape at the range's true coordinates.
Layer — the boundary of a z-slot
A Layer renders one invisible, view-sized div — never painted, never a hit target
(pointer-events:none; children opt back in). Its DOM presence is what gives everything inside it
its layer membership, and with it:
- z-slot — the layer's position in the grid's stack. It orders painting (its children paint after lower layers' children) and event dispatch (its subtree — and its tap — get their turn before lower layers). One number, both axes, so what you see on top is what gets the event first.
- event tap — the layer's own handlers (
onPointerMove,onKeyDown, …): the outermost handlers of its own subtree, and grid-wide ears at its slot on every other layer's turn — heard whatever is under the pointer. Plain React handlers; consume withevent.stopPropagation().event.targetis the real DOM element under the pointer — enough to anchor a tooltip or scope a context menu from a layer that draws nothing (see the element contract).
const pane = useGridPane();
{/* a grid-wide hover tracker: draws nothing, just ears at its slot */}
<Layer onPointerMove={(e) => setHovered(pane.getCellFromPointer(e.clientX, e.clientY))} />
{/* a composite: one z-slot, one gesture, several visuals */}
<Layer zIndex={100}
onPointerDown={startDrag} onPointerMove={updateDrag} onPointerUp={endDrag}>
<RangeRect range={selection} stroke="var(--accent)" alignWidth={2} />
<VirtualDiv range={handleRange} style={{ cursor: 'grab' }} />
</Layer>Inside a Layer, useLayer() reads the slot:
const { zIndex, pane } = useLayer();zIndex is the layer's effective order in the stack (declaration order with explicit-zIndex
overrides folded in) — composites use it to register commands / responders at their layer's real
position. pane is the enclosing grid pane (useGridPane() also works anywhere). The Layer's
boundary div is internal (it never paints and is never a hit target) — a widget that needs a DOM
node is a VirtualDiv, and takes a regular React ref.
The four laws
- z belongs to Layers. VirtualDivs stack by DOM order within their Layer and do not set CSS
z-index. To restack something, move it (or its Layer) in the stack. This is what keeps paint order and dispatch order the same thing. - A Layer never paints and is never a hit target. Its div exists to contain, not to show:
pointer-events:none, no visuals. If a group needs a real container —overflowclipping, groupopacity/filter, a scroll-carrying transform, a paint target — put a<VirtualDiv fill>inside the Layer. The container is then visible in the model instead of smuggled in. - One ordered bubble — layers on top hear events first, keys and pointers alike. An event
visits the stack top-down: each layer's turn runs its own subtree exactly as React does (your
inner elements, then the layer's tap as the boundary), then the next layer down, then the grid's
own behavior, then the command system. The layer that owns the event's target gets its turn in
order — not early.
stopPropagation()is the only consume signal, for every event type. (Targeted events —enter/leave,focus/blur— keep plain per-element DOM semantics; keys go to taps in the same top-down order, and to the focused element at its layer's turn.) - The stack is flat. Layers exist only as direct children of the grid; a Layer's z-slot is
simply its position in that one list (with explicit
zIndexoverrides folded in).
Events
One law covers every event, key and pointer alike — law 3, one ordered bubble: layers on top
hear events first. The event visits the stack top-down; each layer's turn is "standard child
eventing" inside its own boundary — your inner elements dispatch exactly as normal React (a
<button> inside your VirtualDiv behaves untouched), ending at the layer's own tap handlers — and
if nobody stopPropagation()s, the next layer down gets its turn. The layer that owns the event's
target is not special: it gets its turn at its slot, after every layer above it. Whatever nothing
consumed falls to the grid's own behavior (selection / hover / context menu — just the bottom of
the stack), and for keys, on to the command system (the terminal handler of the same bubble).
This holds for keys too: a layer above a focused editor hears keystrokes first — an
autocomplete tip can observe them (build suggestions, don't stop them) or steal them
(stopPropagation) — and the focused input receives them at its own layer's turn, none the wiser.
stopPropagation() is the single consume signal — the same one you already use on any div:
{/* should block the grid: say so, exactly like on a plain page */}
<VirtualDiv range={range}>
<button onClick={(e) => { e.stopPropagation(); doThing(); }}>Click me</button>
</VirtualDiv>
{/* should NOT block the grid: just don't stop it */}
<VirtualDiv range={range} onPointerMove={trackHover} />
{/* decoration: never a hit target at all */}
<VirtualDiv range={range} style={{ pointerEvents: 'none', background: 'rgba(0,0,0,0.06)' }} />Consuming is per event type and is your handler's own one-line decision — which gives fine-grained
behavior for free: a link cell stops its click, while its right-click (no handler, nothing
stopped) still reaches the grid's context menu.
| you write | behavior |
| --- | --- |
| <VirtualDiv> + handlers | hittable; handlers fire at its layer's turn; the event continues down the stack unless you stopPropagation() |
| <VirtualDiv style={{ pointerEvents: 'none' }}> | transparent — never a target; falls straight through |
| <Layer onX={…}> | the slot's tap — the outermost handler of its own subtree, and grid-wide ears at its slot on every other layer's turn |
Targeted events keep plain per-element DOM semantics on your elements — onPointerEnter/Leave,
onFocus/Blur (and keys go to the focused element, at its layer's turn) — since they are defined
per element, not per position.
Rule of thumb: a positioned, interactive thing → VirtualDiv (it is the target); a
grid-wide listener → Layer (it observes, in z order).
The element contract
The events a tap hears are real: event.target is the actual element under the pointer, and
pane.getCellFromPointer(e.clientX, e.clientY) resolves the cell — enough to power tooltips,
context menus, hover tracking, and drag gestures from a layer that draws nothing. One consequence
of walk dispatch: on other layers' turns event.currentTarget is the grid's surface, not your
element — a gesture that captures the pointer captures on its own ref (pointer capture is
honored: a captured element owns its stream for the rest of the drag). And because the Layer's
boundary div gives every element inside it its layer membership, this works for anything you host —
plain elements and third-party widgets included:
const pane = useGridPane();
<Layer
onPointerMove={(e) => setHovered(pane.getCellFromPointer(e.clientX, e.clientY))}
onContextMenu={(e) => openMenuFor(e.target as HTMLElement)}
/>Focus & keyboard
The Stage is the grid's surface — focus rests on it, and that's what cell navigation uses.
Programmatically, gridRef.current.focus() (or pane.focus()) focuses the surface. A VirtualDiv
that should take keyboard focus opts in with tabIndex — regular div focus semantics: when it's
focused, keys target it and reach its handlers at its layer's turn (after the taps above it, per
law 3), and it may stopPropagation to keep them from the layers below; when the surface is
focused, keys reach the grid and it navigates as usual.
A behavior that belongs to the grid in ready mode — opening the cell editor on a typed key or a
double-click — is the floor's, not the top's: put it on its own Layer at the bottom of the stack
(it then hears only what no widget above consumed) and, for keys, act only when the surface itself
is the event target. A layer that sits high to paint (the editor box) must not carry that
behavior, because its tap would hear every widget's keys first. EditorStartLayer + EditorLayer
are this split.
Keys are positionless, so their walk skips hit-testing: every layer is offered the key, top of
z first, then the command system terminates the bubble. There is no "is the target an input?"
second guess — a widget that wants a key (e.g. a cell editor in edit mode) calls stopPropagation;
one that doesn't (ready mode) lets it bubble on. That's what makes the primitives first-class: drop
a Layer with visuals inside and an onKeyDown and contributed commands, and it slots
into the same bubble with no wiring.
Stacking
Layers stack by declaration order — last is on top, like DOM siblings. A layer's zIndex prop
overrides that. Visual stacking and event order stay coupled — the layer you see on top is offered
the event first. Within a layer, children stack by DOM order (law 1).
| Layer band | zIndex | Examples | | --- | --- | --- | | Backgrounds | < 0 | fills, highlights, hover states | | Cells & gridlines | 0 | cell content (default) | | Annotations | 1–99 | borders, badges, validation markers | | Interactive | 100+ | editors, drag handles, movables |
Pop-ups that must float above everything (menus, tooltips) generally portal out of the grid rather than ride an in-grid z-band — see Anchored floats.
Conveniences
Everything else in the package is composed from the two primitives. You could write each of these yourself; they're shipped because they encode non-obvious geometry.
RangeRect — crisp vector outlines & fills
The common decoration: one device-aligned outline/fill at a range. The stroke lines up exactly with gridlines and the selection rectangle at any device-pixel ratio:
<RangeRect
range={{ colStart: 2, rowStart: 2, colEnd: 5, rowEnd: 6 }}
stroke="#1976d2"
alignWidth={2} // device px; even = grows outward, odd = centered
fill="rgba(25,118,210,0.1)"
strokeDasharray="3 2" // optional: marching-ants style
/>Composition: a view-sized, pointer-transparent VirtualDiv hosting a RectangleSVG drawn at
the range's true coordinates (clamped to the view). The box is view-sized on purpose — a range-sized
box would be enormous for whole-column ranges, and an SVG whose box moves can't animate its stroke
(a glide — see RangeGlide — moves the path inside a stable coordinate space instead). RectangleSVG /
LineSVG are available for composing your own shapes the same way.
Anchored floats
Floats attach content to a grid location but escape grid space — they portal out of the grid's clipping and stacking (tooltips, toolbars, prompts). They're built above the primitives (an anchor resolver + Floating UI), not from them:
StickyAnchor— resolves a grid anchor (range / cell / edge / point) to a live position; children render inline (clipping with the pane) or self-position via render-prop.StickyPortal— the portal flavor: floats content beside the anchor with flip/shift/clamp.RangeTooltipLayer— the tooltip kind: aLayertap probing the hovered cell + aStickyPortalin the group's bubble;TooltipProvidersets the timing, the bubble and the single-open group.RangePrompt— a persistent prompt pinned to a range, with an out-of-view "go to" affordance.
Naming convention: a component ending in -Layer roots a Layer (drop it in as a grid child);
anything else composes inside one.
Range handles & gestures
The controlled interaction pieces a selection-style feature composes — each takes a range in and
reports the result range out through onDrag* callbacks:
Draggable— makes its children movable (whole-rectangle or border-ring grip); translate by cell deltas with edge auto-scroll.RangeResizer— an outlined range with corner/edge grips; Excel-style flip-through resizing.FillHandle— the fill corner: drag to extend along one axis, with a dashed preview.DragHandle— the generic corner/edge grip primitive the above are built from.
Built-in feature layers
Complete, drop-in layers (each roots its own Layer — stack them like any other grid child):
CellLayer/GridlineLayer— the cells and gridlinesGridcomposes for you; use them directly on aGridSurfacewhen you own the stack.SelectionLayer— pointer + keyboard selection over anISelectionmodel, with move grip and fill handle slots.EditorStartLayer— the ready-mode edit starters (typed key / F2 / double-click); mount it first (the floor).EditorLayer— an always-mounted inline cell editor (swappable input); mount it last (the top).RangesPickerLayer— multi-rectangle range picking (formula references, chart ranges).List— a virtualized list built from the same engine (a one-column grid + selection).
Using the pane context
Inside any layer or VirtualDiv, reach the live pane with useGridPane():
import { useGridPane } from '@sheetxl/grid-react';
function MyOverlay() {
const pane = useGridPane();
const visible = pane.getVisibleRange();
const bounds = pane.getBoundsFromRange({ colStart: 0, rowStart: 0, colEnd: 5, rowEnd: 5 });
return <VirtualDiv bounds={bounds} style={{ outline: '1px solid green' }} />;
}Key IGridPane methods:
- Queries —
getVisibleRange(),getZoom(),getPaneBounds(),getAnchor() - Coordinates —
getBoundsFromRange(range),getCellFromPointer(x, y),toClipBounds(bounds, insets?) - Interaction —
focus(options?),setPointerCapture(id),getElement(),addReactEventListener(type, listener)
Architecture
Grid (cells + gridlines + scrollbars + headers)
└─ GridSurface (the pure engine)
└─ GridPane (a viewport section — one per frozen region)
└─ Stage (the per-pane surface: event root + focus + stack container)
└─ Layers (gridlines, cells, and yours — each a z-slot of VirtualDivs, bottom → top)Grid— batteries-included wrapper; composes cells + gridlines as layers onto the surface.GridSurface— the core virtualized engine; everything is built from the two primitives.GridPane— internal viewport section; created automatically for freeze panes. Reach it withuseGridPane().Stage— the per-pane surface element. It holds focus and is the root every event converges to. You rarely touch it directly.
Freeze panes
Freeze rows/columns to keep headers in view while scrolling:
<Grid freezeTop={1} freezeLeft={1} renderCells={renderCell} />Layers and VirtualDivs render correctly in every frozen region automatically — no manual handling.
Hidden rows / columns
For the simple case, return true from hiddenCellAt to skip a cell:
<Grid hiddenCellAt={(cell) => cell.rowIndex === 5} renderCells={renderCell} />For row/column-level hiding (used by virtualization), hiddenRowsAt(index, forward) /
hiddenColumnsAt(index, forward) return the next visible index in the given direction.
Performance
- Keep
renderCellspure and fast; avoiduseState/useEffectinside it;React.memocomplex cells; returnnullfor empty cells. - For sparse data, supply
getVisibleCells(pane)to return only the cells that have data. - Minimize layers; prefer declaration order over
zIndex; mark decorationspointer-events: none. - For outlines/fills over huge ranges (whole rows/columns), use
RangeRect— never a range-sizedVirtualDiv.
const Cell = memo(({ style, value }: CellRendererProps) => {
if (!value) return null;
return <div style={style}>{value}</div>;
});Coordinate systems
| System | Units | Example |
| --- | --- | --- |
| Cell | row/column indices | { rowIndex: 5, colIndex: 3 } |
| Range | cell spans | { colStart: 0, rowStart: 0, colEnd: 3, rowEnd: 5 } |
| Bounds | CSS pixels (grid space) + size | { x: 100, y: 200, width: 300, height: 50 } |
Convert with IGridPane: getBoundsFromRange(range), getCellFromPointer(x, y), toClipBounds(bounds).
API reference
Grid props
Required: rowCount, columnCount, renderCells.
Layout: getRowHeight?: number | (index) => number, getColumnWidth?: number | (index) => number,
freezeTop?, freezeLeft?.
Display: showGridLines?: boolean, gridLineColor?.
Layers: children (above the cells), renderBelow? (below the cells), renderBorders?.
Data: getVisibleCells?(pane), hiddenCellAt?(cell), hiddenRowsAt?(index, forward),
hiddenColumnsAt?(index, forward).
Events: onViewportChange?, onFirstRender?(grid).
GridSurface takes the same props minus the cell/gridline conveniences (no renderCells,
getRowHeight, showGridLines) and plus metrics?: IGridMetrics.
See the full API reference for complete types.
Learn more
🔗 Learn More
Whether you're ready to build, need help, or just want to see more examples, here's where to go next.
- 💬 Join our Discord Community - Get help and connect with the team.
- ⭐ Star us on GitHub - If you like SheetXL give us a star ⭐ and help others find us!
- 📘 Developer Docs - Guides and tutorials.
- 🔌 API Reference - Detailed documentation for all packages.
- 👀 Live Demo Gallery - A showcase of interactive examples.
- 🖼️ Storybook - Explore and test individual UI components.
- 🌐 Website - Our Website.
