🚀 BlockNote AI is here! Access the early preview.
Examples/Interoperability/Converting Blocks to Markdown

Converting Blocks to Markdown

This example exports the current document (all blocks) as Markdown and displays it below the editor.

Try it out: Edit the document to see the Markdown representation!

Relevant Docs:

import "@blocknote/core/fonts/inter.css";
import { BlockNoteView } from "@blocknote/mantine";
import "@blocknote/mantine/style.css";
import { useCreateBlockNote } from "@blocknote/react";
import { useEffect, useState } from "react";

import "./styles.css";

export default function App() {
  // Stores the editor's contents as Markdown.
  const [markdown, setMarkdown] = useState<string>("");

  // Creates a new editor instance with some initial content.
  const editor = useCreateBlockNote({
    initialContent: [
      {
        type: "paragraph",
        content: [
          "Hello, ",
          {
            type: "text",
            text: "world!",
            styles: {
              bold: true,
            },
          },
        ],
      },
    ],
  });

  const onChange = async () => {
    // Converts the editor's contents from Block objects to Markdown and store to state.
    const markdown = await editor.blocksToMarkdownLossy(editor.document);
    setMarkdown(markdown);
  };

  useEffect(() => {
    // on mount, trigger initial conversion of the initial content to md
    onChange();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  // Renders the editor instance, and its contents as Markdown below.
  return (
    <div className={"wrapper"}>
      <div>Input (BlockNote Editor):</div>
      <div className={"item"}>
        <BlockNoteView editor={editor} onChange={onChange} />
      </div>
      <div>Output (Markdown):</div>
      <div className={"item bordered"}>
        <pre>
          <code>{markdown}</code>
        </pre>
      </div>
    </div>
  );
}
.wrapper {
  display: flex;
  flex-direction: column;
  height: 100%;
}

.item {
  border-radius: 0.5rem;
  flex: 1;
  overflow: hidden;
}

.item.bordered {
  border: 1px solid gray;
}

.item pre {
  border-radius: 0.5rem;
  height: 100%;
  overflow: auto;
  padding-block: 1rem;
  padding-inline: 54px;
  width: 100%;
  white-space: pre-wrap;
}