Show presence
Paint the selections of remote users into the grid with the data-grid-presence add-on, without a re-render of any row or cell.
The data-grid-presence add-on paints the selections of other users on top of the cells. You feed it from your own transport, for example a websocket or a CRDT. A new highlight list re-renders the overlay layer and no row or cell.
Click a header to sort: Ada's and Grace's highlights are fixed to view positions and jump around, but Linus's 2×2 range is tied to its row ids and keeps following the same rows — a local filter that splits the range paints one labeled rect per fragment.
pnpm dlx shadcn@latest add @gridcn/data-grid-presence
Wire the plugin
useDataGridPresence() returns a plugin and the setters. Call it once per grid, in the component that renders the grid. Every further call creates another store, and only the plugin in plugins paints.
This grid paints the list of highlights that a websocket sends:
"use client";
import { useEffect } from "react";
import { DataGrid, defineColumns } from "@/components/data-grid/data-grid";
import { useDataGridPresence, type PresenceHighlightEntry } from "@/components/data-grid-presence/data-grid-presence";
type Row = { id: string; name: string };
const columns = defineColumns<Row>()([
{ id: "name", header: "Name", accessorKey: "name" },
]);
export function MyGrid({ rows, roomId }: { rows: Row[]; roomId: string }) {
const { plugin, setPresenceHighlights } = useDataGridPresence();
useEffect(() => {
const socket = new WebSocket(`wss://api.example.com/rooms/${roomId}`);
socket.onmessage = (event: MessageEvent<string>) => {
setPresenceHighlights(JSON.parse(event.data) as PresenceHighlightEntry[]);
};
return () => socket.close();
}, [setPresenceHighlights, roomId]);
return (
<DataGrid
data={rows}
columns={columns}
getRowId={(row) => row.id}
plugins={[plugin]}
/>
);
}The identity of plugin never changes, so the inline [plugin] array is safe. Pass the setters down as props to share them.
Describe a highlight
setPresenceHighlights takes an array of entries. The three forms mix freely in one array. Give each entry a unique id. A user with several ranges sends one entry per range.
| Form | Fields | Paints |
|---|---|---|
| Cell | id, color, rowId, columnId, label? | One cell. |
| Row-id range | id, color, rowIds, columnIds, label? | The cells at the crossing of the rows and the columns. |
| View range | id, color, range, label? | The rect range, in view indices. |
color is any CSS color or a token such as var(--color-primary). label shows as a name chip at the top-left corner of each painted rect.
The setter replaces the whole list, so each call carries the full current set of remote entries. To remove entries without a full list, use the two other setters. This hook handles a full list, a leaving peer, and a closed room:
import { useEffect } from "react";
import { useDataGridPresence, type PresenceHighlightEntry } from "@/components/data-grid-presence/data-grid-presence";
type Message =
| { type: "presence"; entries: PresenceHighlightEntry[] }
| { type: "leave"; id: string }
| { type: "room-closed" };
export function usePeerSync(roomId: string) {
const {
plugin,
setPresenceHighlights,
removePresenceHighlight,
clearPresenceHighlights,
} = useDataGridPresence();
useEffect(() => {
const socket = new WebSocket(`wss://api.example.com/rooms/${roomId}`);
socket.onmessage = (event: MessageEvent<string>) => {
const message = JSON.parse(event.data) as Message;
if (message.type === "presence") setPresenceHighlights(message.entries);
else if (message.type === "leave") removePresenceHighlight(message.id);
else clearPresenceHighlights();
};
return () => socket.close();
}, [
roomId,
setPresenceHighlights,
removePresenceHighlight,
clearPresenceHighlights,
]);
return { plugin, setPresenceHighlights };
}Use this hook in place of the call in MyGrid. Each peer has one entry with the peer id as its id. A peer with several ranges holds one entry per range. Give its entries ids such as ${peerId}:0, and remove each one, or send the full list again with setPresenceHighlights.
removePresenceHighlight(id) removes the entry with that id. If no entry matches, it does nothing. clearPresenceHighlights() removes every entry. The grid drops an entry with a malformed range, rowId, columnId, rowIds, or columnIds, and warns once in development. It repairs a bad label: see Presence options.
Send row ids, not view indices
A view range holds indices into the view of the sender. If the receiver sorts or filters differently, the highlight lands on the wrong cells. When sender and receiver views can differ, use the cell form and the row-id range form.
The plugin resolves the ids against the view of the receiver when it paints. It drops a row that a filter hides. It also drops a row that the grid does not hold, such as a row on another page or an unloaded row in scroll mode. It drops a hidden or unknown column and warns once in development. A filter that splits a range paints one rect per contiguous fragment.
One range entry paints at most 1024 fragments. The overlay drops the excess and calls onExcessRects({ entry, kept, total }) each time the kept and total of an entry over the cap change. See Presence options for maxRects and the development warning.
isRowIdPresenceHighlight(entry) and isRowIdRangePresenceHighlight(entry) narrow a received entry to the cell form or the row-id range form. useDataGridRowIdToViewRow() returns the ReadonlyMap<string, number> from row id to view row.
A row move, a column move, a sort, a filter, or a data replacement while a view-range entry is active warns once in development.
Keep rows and cells out of it
A call to setPresenceHighlights re-renders DataGridOverlays only. No row, no cell, and no aria-selected changes. To read the list elsewhere, pass storeApi from the hook to useDataGridPresenceHighlights(storeApi). That hook re-renders only the component that calls it.
How highlights look
- Highlights clamp to the rendered rows and split at pinned columns.
colorbecomes the--presence-colorof the overlay node. The border has full opacity, and the fill is translucent, so two overlapping highlights stay readable.- A
colorthat is invalid, or a theme token that is not defined, paints asvar(--color-primary). - The name chip text is black on light colors and white on dark ones. The switch sits at an OKLCH lightness of 0.62. Without relative color syntax, the text is white. Set
--presence-label-foregroundto use one fixed text color. - Highlights paint below the local active-cell ring. They are
aria-hiddenandpointer-events-none, and never reach the local selection.
Limits
- Presence paints on data rows. Pinned row bands have no highlight.
- The add-on draws no cursors, avatars, or roster. Build those yourself.
Broadcast your selection
Broadcast your selection sends the selection of the local user to peers.
Related
- Push live values: push values into cells
- Presence options: every option of the add-on
- Plugin model: what a grid plugin is
- State and view index: row ids and view indices