Sign in

Quickstart - Get started with commenting in AG Grid using Liveblocks and Next.js

Liveblocks is a realtime collaboration infrastructure for building performant collaborative experiences. Follow the following steps to start adding a commenting experience to your Next.js /app directory application using the hooks from @liveblocks/react and the components from @liveblocks/react-ui.

Quickstart

  1. Install Liveblocks

    Every package should use the same version.

    Terminal
    npm install @liveblocks/client @liveblocks/react @liveblocks/react-ui ag-grid-react
  2. Initialize the liveblocks.config.ts file

    We can use this file later to define types for our application.

    Terminal
    npx create-liveblocks-app@latest --init --framework react
  3. Define thread metadata

    Inside the new liveblocks.config.ts file, define the metadata shape for threads. Metadata is used to attach comment threads to table cells.

    liveblocks.config.ts
    declare global {  interface Liveblocks {    ThreadMetadata: {      rowId: string;      columnId: string;    };  }}
    export {};
  4. Import default styles

    The default components come with default styles, you can import them into the root layout of your app or directly into a CSS file with @import.

    app/layout.tsx
    import "@liveblocks/react-ui/styles.css";
  5. Create a Liveblocks room

    Liveblocks uses the concept of rooms, separate virtual spaces where people collaborate, and to create a realtime experience, multiple users must be connected to the same room. When using Next.js’ /app router, we recommend creating your room in a Room.tsx file in the same directory as your current route.

    Set up a Liveblocks client with LiveblocksProvider, join a room with RoomProvider, and use ClientSideSuspense to add a loading spinner to your app.

    app/Room.tsx
    "use client";
    import { ReactNode } from "react";import { LiveblocksProvider, RoomProvider, ClientSideSuspense,} from "@liveblocks/react/suspense";
    export function Room({ children }: { children: ReactNode }) { return ( <LiveblocksProvider publicApiKey={""}> <RoomProvider id="my-room"> <ClientSideSuspense fallback={<div>Loading…</div>}> {children} </ClientSideSuspense> </RoomProvider> </LiveblocksProvider> );}
  6. Create thread context for your table

    Use React context to set up cells and thread state for your table with useThreads, allowing cells to retrieve their comments.

    app/CellThreadContext.tsx
    "use client";
    import { useState, createContext, useContext } from "react";import { useThreads } from "@liveblocks/react/suspense";import { ThreadData } from "@liveblocks/client";
    export type OpenCell = { rowId: string; columnId: string } | null;
    type CellThreadContextValue = { threads: ThreadData[]; openCell: OpenCell; setOpenCell: (openCell: OpenCell) => void;};
    const CellThreadContext = createContext<CellThreadContextValue | null>(null);
    export function CellThreadProvider({ children,}: { children: React.ReactNode;}) { const { threads } = useThreads(); const [openCell, setOpenCell] = useState<OpenCell>(null);
    return ( <CellThreadContext.Provider value={{ threads, openCell, setOpenCell }}> {children} </CellThreadContext.Provider> );}
    export function useCellThread(): CellThreadContextValue { const context = useContext(CellThreadContext); if (!context) { throw new Error("useCellThread must be used within CellThreadProvider"); } return context;}
  7. Create a custom comment cell

    Create a custom cell renderer for your table that displays comment buttons alongside cell values using FloatingComposer, FloatingThread, and the context we created. Clicking the buttons opens popovers for creating or viewing comment threads.

    app/CommentCell.tsx
    "use client";
    import { Comment, FloatingComposer, FloatingThread,} from "@liveblocks/react-ui";import { CustomCellRendererProps } from "ag-grid-react";import { useCellThread } from "./CellThreadContext";
    export function CommentCell(params: CustomCellRendererProps) { const { threads, openCell, setOpenCell } = useCellThread();
    const rowId = params.data?.id; const columnId = params.colDef?.field;
    if (!rowId || !columnId) { return null; }
    // Check if there's already a thread for this cell const thread = threads.find( ({ metadata }) => metadata.rowId === rowId && metadata.columnId === columnId, );
    // When a thread is created, open it by default const defaultOpen = openCell !== null && openCell.rowId === rowId && openCell.columnId === columnId;
    const metadata = { rowId, columnId };
    return ( <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", gap: 16, }} > {/* Cell contents */} {params.value}
    {/* Show thread if it exists, otherwise show thread composer */} {!thread ? ( <FloatingComposer metadata={metadata} onComposerSubmit={() => setOpenCell(metadata)} style={{ zIndex: 10 }} > <button></button> </FloatingComposer> ) : ( <FloatingThread thread={thread} defaultOpen={defaultOpen} onOpenChange={(isOpen) => { if (!isOpen && defaultOpen) { setOpenCell(null); } }} onComposerSubmit={() => setOpenCell(metadata)} style={{ zIndex: 10 }} autoFocus > <Comment.Avatar style={{ width: 28, height: 28, borderRadius: "100%", cursor: "pointer", }} userId={thread.comments[0]?.userId} /> </FloatingThread> )} </div> );}
  8. Use Liveblocks hooks and components with AG Grid

    Set up AG Grid with AgGridProvider, and add your custom CellThreadProvider context. Import your CommentCell component into defaultColDef, and replace the table data with your own. Learn more on the AG Grid website.

    app/CollaborativeApp.tsx
    "use client";
    import { useState, useMemo } from "react";import { AllCommunityModule } from "ag-grid-community";import { AgGridProvider, AgGridReact } from "ag-grid-react";import { CellThreadProvider } from "./CellThreadContext";import { CommentCell } from "./CommentCell";
    const modules = [AllCommunityModule];
    type RowData = { id: string; name: string; price: number };
    export function CollaborativeApp() { const [rowData] = useState<RowData[]>([ { id: "1", name: "Laptop", price: 1000 }, { id: "2", name: "Phone", price: 500 }, { id: "3", name: "Tablet", price: 300 }, ]);
    const [colDefs] = useState<{ field: keyof RowData }[]>([ { field: "name" }, { field: "price" }, ]);
    const defaultColDef = useMemo( () => ({ cellRenderer: CommentCell, }), [], );
    return ( <AgGridProvider modules={modules}> <CellThreadProvider> <div style={{ height: 500 }}> <AgGridReact rowData={rowData} columnDefs={colDefs} defaultColDef={defaultColDef} getRowId={(params) => params.data.id} /> </div> </CellThreadProvider> </AgGridProvider> );}
  9. Add the Liveblocks room to your page

    Import your room into your page.tsx file, and place your collaborative app components inside it.

    app/page.tsx
    import { Room } from "./Room";import { CollaborativeApp } from "./CollaborativeApp";
    export default function Page() { return ( <Room> <CollaborativeApp /> </Room> );}
  10. Next: authenticate and add your users

    Comments is set up and working now inside AG Grid, but each user is anonymous—the next step is to authenticate each user as they connect, and attach their name and avatar to their comments.

    Add your users to Comments

What to read next

Congratulations! You’ve set up the foundation to start building a commenting experience for your Next.js application.


Examples using Next.js