Sign in

Get started with a CodeMirror code editor using Liveblocks and React

Liveblocks is a realtime collaboration infrastructure for building performant collaborative experiences. Follow the following steps to start adding collaboration to your React application using the APIs from the @liveblocks/codemirror package.

Quickstart

  1. Install Liveblocks and CodeMirror

    Every Liveblocks package should use the same version.

    Terminal
    npm install @liveblocks/client @liveblocks/react @liveblocks/codemirror codemirror
  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

    Add types for your CodeMirror document and presence:

    liveblocks.config.ts
    import type { LiveblocksCodemirrorSelection } from "@liveblocks/codemirror";import { LiveText } from "@liveblocks/client";
    declare global { interface Liveblocks { Presence: { selection: LiveblocksCodemirrorSelection | null; }; Storage: { document: LiveText; }; UserMeta: { id?: string; info?: { name?: string; color?: string; }; }; }}
    export {};
  3. Set up the Liveblocks client

    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. Set up a Liveblocks client with LiveblocksProvider, and join a room with RoomProvider.

    Store your editor document in Storage as LiveText, and set an initial presence shape for cursors.

    App.tsx
    "use client";
    import { LiveText } from "@liveblocks/client";import { LiveblocksProvider, RoomProvider,} from "@liveblocks/react/suspense";import { Editor } from "./Editor";
    export default function App() { return ( <LiveblocksProvider publicApiKey={""}> <RoomProvider id="my-room" initialPresence={{ selection: null }} initialStorage={{ document: new LiveText("Hello, world") }} > {/* ... */} </RoomProvider> </LiveblocksProvider> );}
  4. Join a Liveblocks room

    After setting up the room, you can add collaborative components inside it, using ClientSideSuspense to add loading spinners to your app.

    App.tsx
    "use client";
    import { LiveText } from "@liveblocks/client";import { LiveblocksProvider, RoomProvider, ClientSideSuspense,} from "@liveblocks/react/suspense";import { Editor } from "./Editor";
    export default function App() { return ( <LiveblocksProvider publicApiKey={""}> <RoomProvider id="my-room" initialPresence={{ selection: null }} initialStorage={{ document: new LiveText("Hello, world") }} > <ClientSideSuspense fallback={<div>Loading…</div>}> <Editor /> </ClientSideSuspense> </RoomProvider> </LiveblocksProvider> );}
  5. Set up the collaborative CodeMirror editor

    Now that Liveblocks is set up, create a CodeMirror editor in Editor.tsx. Use createLiveblocksSyncPlugin to sync the document with Storage, and createLiveblocksPresencePlugin to show remote carets and selections.

    Editor.tsx
    "use client";
    import { useCallback, useEffect, useRef, useSyncExternalStore } from "react";import { EditorView } from "@codemirror/view";import { EditorState } from "@codemirror/state";import type { LiveText, Room } from "@liveblocks/client";import { createLiveblocksPresencePlugin, createLiveblocksSyncPlugin,} from "@liveblocks/codemirror";import { useRoom } from "@liveblocks/react/suspense";
    export function Editor() { const room = useRoom(); const root = useRoot(room);
    if (root == null) { return <div>Loading…</div>; }
    return <EditorInner text={root.get("document")} />;}
    function EditorInner({ text }: { text: LiveText }) { const room = useRoom(); const containerRef = useRef<HTMLDivElement>(null);
    useEffect(() => { if (containerRef.current === null) return;
    const view = new EditorView({ parent: containerRef.current, state: EditorState.create({ doc: text.toString(), extensions: [ createLiveblocksSyncPlugin(room, text), createLiveblocksPresencePlugin(room, text), ], }), });
    return () => { view.destroy(); }; }, [room, text]);
    return <div ref={containerRef} className="editor" />;}
    function useRoot(room: Room) { const subscribe = room.events.storageDidLoad.subscribeOnce; const getSnapshot = room.getStorageOrNull; const getServerSnapshot = useCallback(() => null, []); return useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot);}
  6. Style remote carets and selections

    The presence plugin renders remote carets and selections using the .lb-remote-caret and .lb-remote-selection class names. Add styles for them in your CSS. This package does not ship a stylesheet.

    globals.css
    .editor {  height: 100%;}
    .lb-remote-selection { position: absolute; background-color: color-mix(in srgb, var(--lb-remote-color) 25%, transparent); border-radius: 1px; pointer-events: none; box-sizing: border-box;}
    .lb-remote-caret { position: absolute; width: 0; border-left: 2px solid var(--lb-remote-color); pointer-events: none; box-sizing: border-box;}
    main.tsx
    import "./globals.css";
  7. Next: authenticate and add your users

    Your editor is set up and working now, but each user is anonymous—the next step is to authenticate each user as they connect, and attach their name and color to remote carets.

    Set up authentication and add user information

What to read next

Congratulations! You now have set up the foundation for your collaborative CodeMirror editor inside your React application.

If you prefer to use Yjs with CodeMirror, see the Yjs CodeMirror React quickstart.