Skip to content

feat(static-renderer): add @tiptap/static-renderer to enable static rendering of content#5528

Merged
nperez0111 merged 34 commits intonextfrom
node-view-content
Jan 6, 2025
Merged

feat(static-renderer): add @tiptap/static-renderer to enable static rendering of content#5528
nperez0111 merged 34 commits intonextfrom
node-view-content

Conversation

@nperez0111
Copy link
Contributor

@nperez0111 nperez0111 commented Aug 20, 2024

@tiptap/static-renderer

The @tiptap/static-renderer package provides a way to render a Tiptap/ProseMirror document to any target format, like an HTML string, a React component, or even markdown. It does so, by taking the original JSON of a document (or document partial) and attempts to map this to the output format, by matching against a list of nodes & marks.

Why Static Render?

The main use case for static rendering is to render a Tiptap/ProseMirror document on the server-side, for example in a Next.js or Nuxt.js application. This way, you can render the content of your editor to HTML before sending it to the client, which can improve the performance of your application.

Another use case is to render the content of your editor to another format like markdown, which can be useful if you want to send it to a markdown-based API.

But what makes it static? The static renderer doesn't require a browser or a DOM to render the content. It's a pure JavaScript function that takes a document (as JSON or Prosemirror Node instance) and returns the target format back.

Example

Render a Tiptap document to an HTML string:

import StarterKit from '@tiptap/starter-kit'
import { renderToHTMLString } from '@tiptap/static-renderer'

renderToHTMLString({
  extensions: [StarterKit], // using your extensions
  // we can map nodes and marks to HTML elements
  options: {
    nodeMapping: {
      // custom node mappings
    },
    markMapping: {
      // custom mark mappings
    },
    unhandledNode: ({ node }) => {
      // handle unhandled nodes
      return `[unknown node ${node.type.name}]`
    },
    unhandledMark: ({ mark }) => {
      // handle unhandled marks
      return `[unknown node ${mark.type.name}]`
    },
  },
  // the source content to render
  content: {
    type: 'doc',
    content: [
      {
        type: 'paragraph',
        content: [
          {
            type: 'text',
            text: 'Hello World!',
          },
        ],
      },
    ],
  },
})
// returns: '<p>Hello World!</p>'

Render to a React component:

import StarterKit from '@tiptap/starter-kit'
import { renderToReactElement } from '@tiptap/static-renderer'

renderToReactElement({
  extensions: [StarterKit], // using your extensions
  // we can map nodes and marks to HTML elements
  options: {
    nodeMapping: {
      // custom node mappings
    },
    markMapping: {
      // custom mark mappings
    },
    unhandledNode: ({ node }) => {
      // handle unhandled nodes
      return `[unknown node ${node.type.name}]`
    },
    unhandledMark: ({ mark }) => {
      // handle unhandled marks
      return `[unknown node ${mark.type.name}]`
    },
  },
  // the source content to render
  content: {
    type: 'doc',
    content: [
      {
        type: 'paragraph',
        content: [
          {
            type: 'text',
            text: 'Hello World!',
          },
        ],
      },
    ],
  },
})
// returns a react node that, when evaluated, would be equivalent to: '<p>Hello World!</p>'

There are a number of options available to customize the output, like custom node and mark mappings, or handling unhandled nodes and marks.

API

renderToHTMLString

function renderToHTMLString(options: {
  extensions: Extension[],
  content: ProsemirrorNode | JSONContent,
  options?: TiptapHTMLStaticRendererOptions,
}): string

renderToHTMLString Options

  • extensions: An array of Tiptap extensions that are used to render the content.
  • content: The content to render. Can be a Prosemirror Node instance or a JSON representation of a Prosemirror document.
  • options: An object with additional options.
  • options.nodeMapping: An object that maps Prosemirror nodes to HTML strings.
  • options.markMapping: An object that maps Prosemirror marks to HTML strings.
  • options.unhandledNode: A function that is called when an unhandled node is encountered.
  • options.unhandledMark: A function that is called when an unhandled mark is encountered.

renderToReactElement

function renderToReactElement(options: {
  extensions: Extension[],
  content: ProsemirrorNode | JSONContent,
  options?: TiptapReactStaticRendererOptions,
}): ReactElement

renderToReactElement Options

  • extensions: An array of Tiptap extensions that are used to render the content.
  • content: The content to render. Can be a Prosemirror Node instance or a JSON representation of a Prosemirror document.
  • options: An object with additional options.
  • options.nodeMapping: An object that maps Prosemirror nodes to React components.
  • options.markMapping: An object that maps Prosemirror marks to React components.
  • options.unhandledNode: A function that is called when an unhandled node is encountered.
  • options.unhandledMark: A function that is called when an unhandled mark is encountered.

How does it work?

Each Tiptap node/mark extension can define a renderHTML method which is used to generate default mappings of Prosemirror nodes/marks to the target format. These can be overridden by providing custom mappings in the options. One thing to note is that the static renderer doesn't support node views automatically, so you need to provide a mapping for each node type that you want rendered as a node view. Here is an example of how you can render a node view as a React component:

import { Node } from '@tiptap/core'
import { ReactNodeViewRenderer } from '@tiptap/react'
import StarterKit from '@tiptap/starter-kit'
import { renderToReactElement } from '@tiptap/static-renderer'

// This component does not have a NodeViewContent, so it does not render it's children's rich text content
function MyCustomComponentWithoutContent() {
  const [count, setCount] = React.useState(200)

  return (
    <div className='custom-component-without-content' onClick={() => setCount(a => a + 1)}>
      {count} This is a react component!
    </div>
  )
}

const CustomNodeExtensionWithoutContent = Node.create({
  name: 'customNodeExtensionWithoutContent',
  atom: true,
  renderHTML() {
    return ['div', { class: 'my-custom-component-without-content' }] as const
  },
  addNodeView() {
    return ReactNodeViewRenderer(MyCustomComponentWithoutContent)
  },
})

renderToReactElement({
  extensions: [StarterKit, CustomNodeExtensionWithoutContent],
  options: {
    nodeMapping: {
      // render the custom node with the intended node view React component
      customNodeExtensionWithoutContent: MyCustomComponentWithoutContent,
    },
  },
  content: {
    type: 'doc',
    content: [
      {
        type: 'customNodeExtensionWithoutContent',
      },
    ],
  },
})
// returns: <div class="my-custom-component-without-content">200 This is a react component!</div>

But what if you want to render the rich text content of the node view? You can do that by providing a NodeViewContent component as a child of the node view component:

import { Node } from '@tiptap/core'
import {
  NodeViewContent,
  ReactNodeViewContentProvider,
  ReactNodeViewRenderer
} from '@tiptap/react'
import StarterKit from '@tiptap/starter-kit'
import { renderToReactElement } from '@tiptap/static-renderer'


// This component does have a NodeViewContent, so it will render it's children's rich text content
function MyCustomComponentWithContent() {
  return (
    <div className="custom-component-with-content">
      Custom component with content in React!
      <NodeViewContent />
    </div>
  )
}


const CustomNodeExtensionWithContent = Node.create({
  name: 'customNodeExtensionWithContent',
  content: 'text*',
  group: 'block',
  renderHTML() {
    return ['div', { class: 'my-custom-component-with-content' }, 0] as const
  },
  addNodeView() {
    return ReactNodeViewRenderer(MyCustomComponentWithContent)
  },
})


renderToReactElement({
  extensions: [StarterKit, CustomNodeExtensionWithContent],
  options: {
    nodeMapping: {
      customNodeExtensionWithContent: ({ children }) => {
        // To pass the content down into the NodeViewContent component, we need to wrap the custom component with the ReactNodeViewContentProvider
        return (
          <ReactNodeViewContentProvider content={children}>
            <MyCustomComponentWithContent />
          </ReactNodeViewContentProvider>
        )
      },
    },
  },
  content: {
    type: 'doc',
    content: [
      {
        type: 'customNodeExtensionWithContent',
        // rich text content
        content: [
          {
            type: 'text',
            text: 'Hello, world!',
          },
        ],
      },
    ],
  },
})

// returns: <div class="custom-component-with-content">Custom component with content in React!<div data-node-view-content="" style="white-space:pre-wrap">Hello, world!</div></div>
// Note: The NodeViewContent component is rendered as a div with the attribute data-node-view-content, and the rich text content is rendered inside of it

@changeset-bot
Copy link

changeset-bot bot commented Aug 20, 2024

🦋 Changeset detected

Latest commit: 639e0d7

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 57 packages
Name Type
@tiptap/static-renderer Major
@tiptap/extension-table-header Major
@tiptap/extension-table-cell Major
@tiptap/extension-table-row Major
@tiptap/extension-table Major
@tiptap/extension-text-style Major
@tiptap/core Major
@tiptap/extension-blockquote Major
@tiptap/extension-bold Major
@tiptap/extension-bubble-menu Major
@tiptap/extension-bullet-list Major
@tiptap/extension-character-count Major
@tiptap/extension-code-block-lowlight Major
@tiptap/extension-code-block Major
@tiptap/extension-code Major
@tiptap/extension-collaboration-cursor Major
@tiptap/extension-collaboration Major
@tiptap/extension-color Major
@tiptap/extension-document Major
@tiptap/extension-dropcursor Major
@tiptap/extension-floating-menu Major
@tiptap/extension-focus Major
@tiptap/extension-font-family Major
@tiptap/extension-font-size Major
@tiptap/extension-gapcursor Major
@tiptap/extension-hard-break Major
@tiptap/extension-heading Major
@tiptap/extension-highlight Major
@tiptap/extension-history Major
@tiptap/extension-horizontal-rule Major
@tiptap/extension-image Major
@tiptap/extension-italic Major
@tiptap/extension-link Major
@tiptap/extension-list-item Major
@tiptap/extension-list-keymap Major
@tiptap/extension-mention Major
@tiptap/extension-ordered-list Major
@tiptap/extension-paragraph Major
@tiptap/extension-placeholder Major
@tiptap/extension-strike Major
@tiptap/extension-subscript Major
@tiptap/extension-superscript Major
@tiptap/extension-task-item Major
@tiptap/extension-task-list Major
@tiptap/extension-text-align Major
@tiptap/extension-text Major
@tiptap/extension-typography Major
@tiptap/extension-underline Major
@tiptap/extension-utils Major
@tiptap/extension-youtube Major
@tiptap/html Major
@tiptap/pm Major
@tiptap/react Major
@tiptap/starter-kit Major
@tiptap/suggestion Major
@tiptap/vue-2 Major
@tiptap/vue-3 Major

Not sure what this means? Click here to learn what changesets are.

Click here if you're a maintainer who wants to add another changeset to this PR

@netlify
Copy link

netlify bot commented Aug 20, 2024

Deploy Preview for tiptap-embed ready!

Name Link
🔨 Latest commit 639e0d7
🔍 Latest deploy log https://app.netlify.com/sites/tiptap-embed/deploys/677bd3e82408ab00084e97ca
😎 Deploy Preview https://deploy-preview-5528--tiptap-embed.netlify.app
📱 Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.

To edit notification comments on pull requests, go to your Netlify site configuration.

Copy link
Member

@bdbch bdbch left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM! Awesome idea @nperez0111

@nperez0111 nperez0111 changed the title feat: allowing specifying the content of ReacNodeViewContent via a React Context feat(static-renderer): add @tiptap/static-renderer to enable static rendering of content Aug 27, 2024
@nperez0111
Copy link
Contributor Author

Just as a note, if we render to something like jsx-dom then we can render directly to HTMLElements with pure JS & prosemirror

@dcneiner
Copy link

dcneiner commented Sep 16, 2024

@nperez0111 I am super excited about this PR (finally took a look at it over the weekend). I tried building it locally today to test it out, and it failed because there was no src/index.ts file in the new static-renderer folder. Is there a pre-build step I was missing? I just added one locally to get past that.

Edit: Ah, its the same error currently failing the build CI step. You are probably already aware of this then!

@nperez0111
Copy link
Contributor Author

@nperez0111 I am super excited about this PR (finally took a look at it over the weekend). I tried building it locally today to test it out, and it failed because there was no src/index.ts file in the new static-renderer folder. Is there a pre-build step I was missing? I just added one locally to get past that.

Edit: Ah, its the same error currently failing the build CI step. You are probably already aware of this then!

Yep, this isn't completely prime-time yet. Needs a lot more tests to ensure things actually work

@bdbch
Copy link
Member

bdbch commented Nov 30, 2024

@nperez0111 I'll remove my review - let me check if I should review in the future.

@bdbch bdbch self-requested a review November 30, 2024 07:47
@nperez0111 nperez0111 changed the base branch from develop to next December 4, 2024 15:34
@nperez0111 nperez0111 force-pushed the node-view-content branch 3 times, most recently from 5645687 to bc7ad50 Compare December 4, 2024 16:05
@pkg-pr-new
Copy link

pkg-pr-new bot commented Dec 4, 2024

Open in Stackblitz

@tiptap/core

npm i https://pkg.pr.new/@tiptap/core@5528

@tiptap/extension-bold

npm i https://pkg.pr.new/@tiptap/extension-bold@5528

@tiptap/extension-blockquote

npm i https://pkg.pr.new/@tiptap/extension-blockquote@5528

@tiptap/extension-bubble-menu

npm i https://pkg.pr.new/@tiptap/extension-bubble-menu@5528

@tiptap/extension-bullet-list

npm i https://pkg.pr.new/@tiptap/extension-bullet-list@5528

@tiptap/extension-character-count

npm i https://pkg.pr.new/@tiptap/extension-character-count@5528

@tiptap/extension-code

npm i https://pkg.pr.new/@tiptap/extension-code@5528

@tiptap/extension-code-block

npm i https://pkg.pr.new/@tiptap/extension-code-block@5528

@tiptap/extension-code-block-lowlight

npm i https://pkg.pr.new/@tiptap/extension-code-block-lowlight@5528

@tiptap/extension-collaboration

npm i https://pkg.pr.new/@tiptap/extension-collaboration@5528

@tiptap/extension-collaboration-cursor

npm i https://pkg.pr.new/@tiptap/extension-collaboration-cursor@5528

@tiptap/extension-color

npm i https://pkg.pr.new/@tiptap/extension-color@5528

@tiptap/extension-document

npm i https://pkg.pr.new/@tiptap/extension-document@5528

@tiptap/extension-dropcursor

npm i https://pkg.pr.new/@tiptap/extension-dropcursor@5528

@tiptap/extension-floating-menu

npm i https://pkg.pr.new/@tiptap/extension-floating-menu@5528

@tiptap/extension-focus

npm i https://pkg.pr.new/@tiptap/extension-focus@5528

@tiptap/extension-font-family

npm i https://pkg.pr.new/@tiptap/extension-font-family@5528

@tiptap/extension-font-size

npm i https://pkg.pr.new/@tiptap/extension-font-size@5528

@tiptap/extension-gapcursor

npm i https://pkg.pr.new/@tiptap/extension-gapcursor@5528

@tiptap/extension-hard-break

npm i https://pkg.pr.new/@tiptap/extension-hard-break@5528

@tiptap/extension-heading

npm i https://pkg.pr.new/@tiptap/extension-heading@5528

@tiptap/extension-highlight

npm i https://pkg.pr.new/@tiptap/extension-highlight@5528

@tiptap/extension-history

npm i https://pkg.pr.new/@tiptap/extension-history@5528

@tiptap/extension-horizontal-rule

npm i https://pkg.pr.new/@tiptap/extension-horizontal-rule@5528

@tiptap/extension-image

npm i https://pkg.pr.new/@tiptap/extension-image@5528

@tiptap/extension-italic

npm i https://pkg.pr.new/@tiptap/extension-italic@5528

@tiptap/extension-link

npm i https://pkg.pr.new/@tiptap/extension-link@5528

@tiptap/extension-list-item

npm i https://pkg.pr.new/@tiptap/extension-list-item@5528

@tiptap/extension-list-keymap

npm i https://pkg.pr.new/@tiptap/extension-list-keymap@5528

@tiptap/extension-mention

npm i https://pkg.pr.new/@tiptap/extension-mention@5528

@tiptap/extension-ordered-list

npm i https://pkg.pr.new/@tiptap/extension-ordered-list@5528

@tiptap/extension-paragraph

npm i https://pkg.pr.new/@tiptap/extension-paragraph@5528

@tiptap/extension-placeholder

npm i https://pkg.pr.new/@tiptap/extension-placeholder@5528

@tiptap/extension-strike

npm i https://pkg.pr.new/@tiptap/extension-strike@5528

@tiptap/extension-superscript

npm i https://pkg.pr.new/@tiptap/extension-superscript@5528

@tiptap/extension-table

npm i https://pkg.pr.new/@tiptap/extension-table@5528

@tiptap/extension-table-cell

npm i https://pkg.pr.new/@tiptap/extension-table-cell@5528

@tiptap/extension-table-header

npm i https://pkg.pr.new/@tiptap/extension-table-header@5528

@tiptap/extension-table-row

npm i https://pkg.pr.new/@tiptap/extension-table-row@5528

@tiptap/extension-task-item

npm i https://pkg.pr.new/@tiptap/extension-task-item@5528

@tiptap/extension-task-list

npm i https://pkg.pr.new/@tiptap/extension-task-list@5528

@tiptap/extension-text

npm i https://pkg.pr.new/@tiptap/extension-text@5528

@tiptap/extension-text-align

npm i https://pkg.pr.new/@tiptap/extension-text-align@5528

@tiptap/extension-typography

npm i https://pkg.pr.new/@tiptap/extension-typography@5528

@tiptap/extension-text-style

npm i https://pkg.pr.new/@tiptap/extension-text-style@5528

@tiptap/extension-utils

npm i https://pkg.pr.new/@tiptap/extension-utils@5528

@tiptap/extension-underline

npm i https://pkg.pr.new/@tiptap/extension-underline@5528

@tiptap/extension-youtube

npm i https://pkg.pr.new/@tiptap/extension-youtube@5528

@tiptap/html

npm i https://pkg.pr.new/@tiptap/html@5528

@tiptap/react

npm i https://pkg.pr.new/@tiptap/react@5528

@tiptap/pm

npm i https://pkg.pr.new/@tiptap/pm@5528

@tiptap/starter-kit

npm i https://pkg.pr.new/@tiptap/starter-kit@5528

@tiptap/static-renderer

npm i https://pkg.pr.new/@tiptap/static-renderer@5528

@tiptap/suggestion

npm i https://pkg.pr.new/@tiptap/suggestion@5528

@tiptap/vue-2

npm i https://pkg.pr.new/@tiptap/vue-2@5528

@tiptap/vue-3

npm i https://pkg.pr.new/@tiptap/vue-3@5528

@tiptap/extension-subscript

npm i https://pkg.pr.new/@tiptap/extension-subscript@5528

commit: 639e0d7

@masylum
Copy link

masylum commented Dec 19, 2024

I think there is a bug when using namespaces:

https://github.com/ProseMirror/prosemirror-model/blob/3c0b054fbdeabbf45836b3441ec8ce5da8da2e5d/src/to_dom.js#L126C1-L131C106

this should work:

renderHTML({ HTMLAttributes, node }) {
	const { iconValue, title } = node.attrs

	return [
		[
			"div",
			{
				"data-type": ALERT_ICON_NODE,
			},
			[
				"http://www.w3.org/2000/svg svg",
				{
					width: 24,
					height: 24,
					"stroke-width": 2,
					stroke: "currentColor",
					"stroke-linecap": "round",
					fill: "none",
				},
				["title", {}, iconValue],
				[
					"use",
					{ "http://www.w3.org/1999/xlink xlink:href": `#${iconValue}` },
				],
			],
		],
	] as any
}

Specifically, the "http://www.w3.org/2000/svg svg"

@nperez0111
Copy link
Contributor Author

Welp, didn't know about that feature, I'll have to get back to you on this

@Richard87
Copy link

Thanks for the quick response! :)

Not directly, since custom react extensions would look like <photo-node src="data:aksjdhf"></photo-node>, so using dangerouslySetInnerHTML wont work.

But I found yesterday after posting, that JSON.serialize retained the attr when executing in the browser (but it was lost when sending the content object to a Next Server Action for serializing there), so my test might be flawed :)

Copy link
Member

@bdbch bdbch left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks good to me. I'm just not sure about all the example files. Is there a reason why they're here?

Afaik we don't have any example files in any of our other packages and we usually did this kind of thing in our demos.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do we need this file in src or is there any reason why we need this?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Same here - do we need this in the src directory? We don't really expose anything to the user and this looks more like a code example we'd expect in the docs?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

See above

return React.createElement(
component as React.FC<typeof props>,
// eslint-disable-next-line no-plusplus
Object.assign(props, { key: key++ }),
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Instead of ignoring the linter we could just do key += 1 here

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

See above

@nperez0111
Copy link
Contributor Author

Yep, yea the .example files were just so I can test things while running it in bun.

I'll see if it makes sense to make demos out of them

@nperez0111 nperez0111 merged commit 6a53bb2 into next Jan 6, 2025
@nperez0111 nperez0111 deleted the node-view-content branch January 6, 2025 13:00
@volarname
Copy link
Contributor

volarname commented Mar 16, 2025

what about vue? really dont want to use v-html

@guqing
Copy link

guqing commented Apr 30, 2025

Hi team 👋,

I’m trying to test this PR using "@tiptap/static-renderer": "3.0.0-beta.3" that includes a custom NodeView using @tiptap/react. I followed the example provided and integrated it into a Next.js project (App Router, app/ directory structure). However, I’m encountering the following error when I run the project:

⨯ TypeError: Class extends value undefined is not a constructor or null

This might be caused by a React Class Component being rendered in a Server Component, React Class Components only work in Client Components.
Read more: https://nextjs.org/docs/messages/class-component-in-server-component

    at src/editor/extensions/nodes/MyCustomComponentWithContent.tsx:2:0
    at src/editor/extensions/nodes/index.ts:2:0
    at src/editor/extensions/index.ts:16:0
    at src/app/api/text/route.ts:9:0
    at Object.<anonymous> (.next/server/app/api/text/route.js:11:9)

The error is triggered by this import line in MyCustomComponentWithContent.tsx:

import { NodeViewWrapper, NodeViewProps, NodeViewContent } from '@tiptap/react';

From what I understand, this may be related to React Class Components not being compatible with Next.js Server Components. But since the extension is used in the editor context, I expected it to only run on the client.

Repro context:

  • Using @tiptap/react
  • Running on Next.js 15.3.1 App Router
  • The NodeView is part of a PR implementation (e.g. < MyCustomComponentWithContent />)

Questions:

Is there a known issue when using NodeViewWrapper inside a Next.js app?

Let me know if you need a minimal repo—I’d be happy to prepare one.

Thanks for your awesome work!

@nperez0111
Copy link
Contributor Author

what about vue? really dont want to use v-html

@volarname static renderer doesn't care what your output is. So you can implement it how you want.

@nperez0111
Copy link
Contributor Author

I’m trying to test this PR using "@tiptap/static-renderer": "3.0.0-beta.3" that includes a custom NodeView using @tiptap/react. I followed the example provided and integrated it into a Next.js project (App Router, app/ directory structure). However, I’m encountering the following error when I run the project:

@guqing You are using the beta version of static renderer, but are you using the correct @tiptap/react version which also needs to be the beta version? This PR made changes to NodeViews as well so it needs the beta version too

@guqing
Copy link

guqing commented May 5, 2025

I’m trying to test this PR using "@tiptap/static-renderer": "3.0.0-beta.3" that includes a custom NodeView using @tiptap/react. I followed the example provided and integrated it into a Next.js project (App Router, app/ directory structure). However, I’m encountering the following error when I run the project:

@guqing You are using the beta version of static renderer, but are you using the correct @tiptap/react version which also needs to be the beta version? This PR made changes to NodeViews as well so it needs the beta version too

Yes, tiptap/react is also on the beta version. Here's a minimal reproducible demo: static-renderer-demo.zip ,It uses the code from this PR example

The following error can be reproduced by accessing localhost:3000 in Node.js 18 or 22:

TypeError: Class extends value undefined is not a constructor or null

This might be caused by a React Class Component being rendered in a Server Component, React Class Components only works in Client Components. Read more: https://nextjs.org/docs/messages/class-component-in-server-component

src/app/page.tsx (4:1) @ [project]/src/app/page.tsx [app-rsc] (ecmascript)


  2 | import StarterKit from "@tiptap/starter-kit";
  3 | import { Node } from '@tiptap/core'
> 4 | import {  ReactNodeViewRenderer } from '@tiptap/react'
    | ^
  5 | import React from 'react'

If use NodeViewWrapper from tiptap/react, NodeViewContent will throw the same error

@nperez0111
Copy link
Contributor Author

nperez0111 commented May 6, 2025

I briefly looked into this @guqing, it seems to be that the @tiptap/react package uses React.Component which is not valid in an RSC. Unfortunately, while the static renderer with ReactNodeViewRenderer works in SSR (on node), it does not work within an RSC.

RSCs impose a few additional constraints that the react package relies on:

  • class components (which is an easy refactor)
  • React contexts and effects (not easy to refactor)

So, this will not be viable to use custom node views via ReactNodeViewRenderer within a Next.js RSC at this point in time. It will require significant effort to refactor this in a way that works both for client and server components.

I no longer work for Tiptap & don't have the capacity to try make these changes myself. I'd suggest you to create a GitHub Issue and link back to my explanation here. Even contribute a PR if you can! Tagging @bdbch for visibility

Your best option at the moment is to remove any references to ReactNodeViewRenderer from reach of the RSC, and implement the nodeMapping yourself. See this example:

import { renderToReactElement } from "@tiptap/static-renderer";
import StarterKit from "@tiptap/starter-kit";
import { Node } from "@tiptap/core";
// import { ReactNodeViewRenderer } from "@tiptap/react";
import React from "react";

// This component does not have a NodeViewContent, so it does not render it's children's rich text content
function MyCustomComponentWithoutContent() {
  // RSCs do not support useState
  // const [count, setCount] = React.useState(200);

  return (
    <div
      className="custom-component-without-content"
      // onClick={() => setCount((a) => a + 1)}
    >
      {/* {count} This is a react component! */}
      This is a react component!
    </div>
  );
}

const CustomNodeExtensionWithoutContent = Node.create({
  name: "customNodeExtensionWithoutContent",
  atom: true,
  renderHTML() {
    return ["div", { class: "my-custom-component-without-content" }] as const;
  },
  // This extension cannot be used with RSCs if it uses the ReactNodeViewRenderer
  // addNodeView() {
  //   return ReactNodeViewRenderer(MyCustomComponentWithoutContent);
  // },
});

export default function Home() {
  return renderToReactElement({
    extensions: [StarterKit, CustomNodeExtensionWithoutContent],
    options: {
      nodeMapping: {
        // render the custom node with the intended node view React component
        customNodeExtensionWithoutContent: MyCustomComponentWithoutContent,
      },
    },
    content: {
      type: "doc",
      content: [
        {
          type: "customNodeExtensionWithoutContent",
          // rich text content
          content: [
            {
              type: "text",
              text: "Hello, world!",
            },
          ],
        },
      ],
    },
  });
}

This example will correctly render the React component in an RSC.

Also you specified your deps incorrectly it should be:

    "@tiptap/react": "3.0.0-beta.4",
    "@tiptap/starter-kit": "3.0.0-beta.4",
    "@tiptap/static-renderer": "3.0.0-beta.4",
    "@tiptap/core": "3.0.0-beta.4",
    "@tiptap/pm": "3.0.0-beta.4"

For future reference:

I asked an LLM to refactor the React.Component usage in the repo and ended up with this diff (which seems about right):

diff --git i/packages/react/src/EditorContent.tsx w/packages/react/src/EditorContent.tsx
index 39f220b5c..5a152784a 100644
--- i/packages/react/src/EditorContent.tsx
+++ w/packages/react/src/EditorContent.tsx
@@ -83,124 +83,107 @@ function getInstance(): ContentComponent {
  }
}

-export class PureEditorContent extends React.Component<
-  EditorContentProps,
-  { hasContentComponentInitialized: boolean }
-> {
-  editorContentRef: React.RefObject<any>
+export const PureEditorContent: React.FC<EditorContentProps> = props => {
+  const { editor: currentEditor, innerRef, ...rest } = props
+  const editorContentRef = React.useRef<HTMLDivElement>(null)
+  const initialized = React.useRef(false)
+  const unsubscribeToContentComponent = React.useRef<(() => void) | undefined>(undefined)

-  initialized: boolean
+  const [hasContentComponentInitialized, setHasContentComponentInitialized] = React.useState(
+    Boolean((currentEditor as EditorWithContentComponent | null)?.contentComponent),
+  )

-  unsubscribeToContentComponent?: () => void
+  React.useEffect(() => {
+    const editor = currentEditor as EditorWithContentComponent | null

-  constructor(props: EditorContentProps) {
-    super(props)
-    this.editorContentRef = React.createRef()
-    this.initialized = false
+    const init = () => {
+      if (editor && !editor.isDestroyed && editor.options.element) {
+        if (editor.contentComponent) {
+          return
+        }

-    this.state = {
-      hasContentComponentInitialized: Boolean((props.editor as EditorWithContentComponent | null)?.contentComponent),
+        const element = editorContentRef.current
+
+        if (element) {
+          element.append(...editor.options.element.childNodes)
+
+          editor.setOptions({
+            element,
+          })
+
+          editor.contentComponent = getInstance()
+
+          // Has the content component been initialized?
+          if (!hasContentComponentInitialized) {
+            // Subscribe to the content component
+            unsubscribeToContentComponent.current = editor.contentComponent.subscribe(() => {
+              setHasContentComponentInitialized(prev => {
+                if (!prev) {
+                  return true
+                }
+                return prev
+              })
+
+              // Unsubscribe to previous content component
+              if (unsubscribeToContentComponent.current) {
+                unsubscribeToContentComponent.current()
+              }
+            })
+          }
+
+          editor.createNodeViews()
+          initialized.current = true
+        }
+      }
    }
-  }

-  componentDidMount() {
-    this.init()
-  }
+    init()

-  componentDidUpdate() {
-    this.init()
-  }
+    return () => {
+      // This is the cleanup function, equivalent to componentWillUnmount
+      const editorUnmount = currentEditor as EditorWithContentComponent | null

-  init() {
-    const editor = this.props.editor as EditorWithContentComponent | null
-
-    if (editor && !editor.isDestroyed && editor.options.element) {
-      if (editor.contentComponent) {
+      if (!editorUnmount) {
        return
      }

-      const element = this.editorContentRef.current
+      initialized.current = false

-      element.append(...editor.options.element.childNodes)
-
-      editor.setOptions({
-        element,
-      })
-
-      editor.contentComponent = getInstance()
-
-      // Has the content component been initialized?
-      if (!this.state.hasContentComponentInitialized) {
-        // Subscribe to the content component
-        this.unsubscribeToContentComponent = editor.contentComponent.subscribe(() => {
-          this.setState(prevState => {
-            if (!prevState.hasContentComponentInitialized) {
-              return {
-                hasContentComponentInitialized: true,
-              }
-            }
-            return prevState
-          })
-
-          // Unsubscribe to previous content component
-          if (this.unsubscribeToContentComponent) {
-            this.unsubscribeToContentComponent()
-          }
+      if (!editorUnmount.isDestroyed) {
+        editorUnmount.view.setProps({
+          nodeViews: {},
        })
      }

-      editor.createNodeViews()
+      if (unsubscribeToContentComponent.current) {
+        unsubscribeToContentComponent.current()
+      }

-      this.initialized = true
-    }
-  }
+      editorUnmount.contentComponent = null

-  componentWillUnmount() {
-    const editor = this.props.editor as EditorWithContentComponent | null
+      if (!editorUnmount.options.element?.firstChild) {
+        return
+      }

-    if (!editor) {
-      return
-    }
+      // TODO using the new editor.mount method might allow us to remove this
+      const newElement = document.createElement('div')

-    this.initialized = false
+      newElement.append(...editorUnmount.options.element.childNodes)

-    if (!editor.isDestroyed) {
-      editor.view.setProps({
-        nodeViews: {},
+      editorUnmount.setOptions({
+        element: newElement,
      })
    }
+    // eslint-disable-next-line react-hooks/exhaustive-deps
+  }, [currentEditor, hasContentComponentInitialized]) // Dependencies for the effect

-    if (this.unsubscribeToContentComponent) {
-      this.unsubscribeToContentComponent()
-    }
-
-    editor.contentComponent = null
-
-    if (!editor.options.element?.firstChild) {
-      return
-    }
-
-    // TODO using the new editor.mount method might allow us to remove this
-    const newElement = document.createElement('div')
-
-    newElement.append(...editor.options.element.childNodes)
-
-    editor.setOptions({
-      element: newElement,
-    })
-  }
-
-  render() {
-    const { editor, innerRef, ...rest } = this.props
-
-    return (
-      <>
-        <div ref={mergeRefs(innerRef, this.editorContentRef)} {...rest} />
-        {/* @ts-ignore */}
-        {editor?.contentComponent && <Portals contentComponent={editor.contentComponent} />}
-      </>
-    )
-  }
+  return (
+    <>
+      <div ref={mergeRefs(innerRef, editorContentRef)} {...rest} />
+      {/* @ts-ignore */}
+      {currentEditor?.contentComponent && <Portals contentComponent={currentEditor.contentComponent} />}
+    </>
+  )
}

// EditorContent should be re-created whenever the Editor instance changes

@guqing
Copy link

guqing commented May 7, 2025

Hi @nperez0111 ,

Thank you so much for taking the time to dig into this and write such a detailed explanation. 🙏
I’ll open a dedicated issue that links back to your comment (and tag @bdbch) so the core team can triage it properly.
Really appreciate your guidance! 🚀

Thanks again

@tasiotas
Copy link

please document how to use static renderer with Vue. Its great to see it with React, but its not clear how to make it work with Vue.

what about vue? really dont want to use v-html

@volarname static renderer doesn't care what your output is. So you can implement it how you want.

@nperez0111
Copy link
Contributor Author

please document how to use static renderer with Vue. Its great to see it with React, but its not clear how to make it work with Vue.

Feel free to contribute, I don't know vue well enough to do that and have no need for this myself

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

8 participants