Converting Blocks to HTML
This example exports the current document (all blocks) as HTML and displays it below the editor.
Try it out: Edit the document to see the HTML 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 HTML.
const [html, setHTML] = 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 HTML and store to state.
const html = await editor.blocksToHTMLLossy(editor.document);
setHTML(html);
};
useEffect(() => {
// on mount, trigger initial conversion of the initial content to html
onChange();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
// Renders the editor instance and HTML output.
return (
<div className="views">
<div className="view-wrapper">
<div className="view-label">Editor Input</div>
<div className="view">
<BlockNoteView editor={editor} onChange={onChange} />
</div>
</div>
<div className="view-wrapper">
<div className="view-label">HTML Output</div>
<div className="view">
<pre>
<code>{html}</code>
</pre>
</div>
</div>
</div>
);
}
.views {
container-name: views;
container-type: inline-size;
display: flex;
flex-direction: row;
flex-wrap: wrap;
gap: 8px;
height: 100%;
padding: 8px;
}
.view-wrapper {
display: flex;
flex-direction: column;
height: calc(50% - 4px);
width: 100%;
}
@container views (width > 1024px) {
.view-wrapper {
height: 100%;
width: calc(50% - 4px);
}
}
.view-label {
color: #0090ff;
display: flex;
font-size: 12px;
font-weight: bold;
justify-content: space-between;
margin-inline: 16px;
}
.view {
border: solid #0090ff 1px;
border-radius: 16px;
flex: 1;
height: 0;
padding: 8px;
}
.view .bn-container {
height: 100%;
margin: 0;
max-width: none;
padding: 0;
}
.view .bn-editor {
height: 100%;
overflow: auto;
}
.view pre {
background-color: #0090ff20;
border-radius: 8px;
flex: 1;
height: 100%;
margin: 0;
overflow: auto;
padding: 8px;
white-space: pre-wrap;
}