Is it possible to have a complete custom renderHTML function in TipTap?

3.9k Views Asked by At

Currently the format is like this:

renderHTML({ HTMLAttributes }) {
    return ['img', mergeAttributes(this.options.HTMLAttributes, HTMLAttributes)];
  },

Now could I do something like this:

renderHTML({ HTMLAttributes }) {
    return <div>hello</div>;
  },

Updated with addNodeView:

So I have now a CustomImage.js:

const CustomImage = Image.extend({
  addNodeView() {
    return ReactNodeViewRenderer(NextImage);
  },
});
export default CustomImage;

And NextImage is:

const NextImage = () => {
  return (
    <NodeViewWrapper>
      <div>hello</div>
    </NodeViewWrapper>
  );
};

export default NextImage;

And I use it like this:

html = generateHTML(JSON.parse(text), [
        CustomImage
   ....
1

There are 1 best solutions below

3
On BEST ANSWER

The renderHtmlfunction is called when you run editor.getHTML()

To answer your question, from my best knowledge it need to match their format. To achieve what you want you could do something like this:

renderHTML({ HTMLAttributes }) {
    // On output
    return [
      "div",
      mergeAttributes(HTMLAttributes), // mergeAttributes is a exported function from @tiptap/core
      "hello",
    ];
  },

If you on the other hand want to render that in the editor you should use:

addNodeView() {
    return ReactNodeViewRenderer(YourComponentHere);
  },

And you can show whatever component you want:

import { NodeViewWrapper } from "@tiptap/react";
import React from "react";

const YourComponentHere = ({ node, updateAttributes, selected, editor }) => {
  return (
    <NodeViewWrapper>
      <div>hello</div>
    </NodeViewWrapper>
  );
};

Edit: Assuming that you are using react, you should use useEditor if you want to use the tiptap editor.

import { useEditor, EditorContent } from '@tiptap/react'
import StarterKit from '@tiptap/starter-kit'
import CustomImage from './CustomImage'

const Tiptap = () => {
  const editor = useEditor({
    extensions: [
      StarterKit,
      CustomImage
    ],
    content: '<p>Your inital content here</p>',
  })

  return (
    <EditorContent editor={editor} />
  )
}

export default Tiptap

https://tiptap.dev/installation/react