PlateJS Serializing HTML

479 views Asked by At

I'm trying to make it so that when I click on a button, I can get an html string. Generally, this rich text editor will be inside the React-Hook-Form and when the form is submitted, it will save the value to html, so it could be saved to the database

Here's my code:

"use client";

import { plugins } from "@/lib/plugins";
import { CommentsProvider } from "@udecode/plate-comments";
import { Plate, createPlateEditor } from "@udecode/plate-common";
import { serializeHtml } from "@udecode/plate-serializer-html";
import { FC } from "react";
import { DndProvider } from "react-dnd";
import { HTML5Backend } from "react-dnd-html5-backend";

import { CommentsPopover } from "@/components/plate-ui/comments-popover";
import { Editor } from "@/components/plate-ui/editor";
import { FixedToolbar } from "@/components/plate-ui/fixed-toolbar";
import { FixedToolbarButtons } from "@/components/plate-ui/fixed-toolbar-buttons";
import { FloatingToolbar } from "@/components/plate-ui/floating-toolbar";
import { FloatingToolbarButtons } from "@/components/plate-ui/floating-toolbar-buttons";
import { MentionCombobox } from "@/components/plate-ui/mention-combobox";

interface PropsType {
  initialValue?: any;
}

const RichTextEditor: FC<PropsType> = ({ initialValue }) => {
  const editor = createPlateEditor({ plugins });

  const html = serializeHtml(editor, {
    nodes: editor.children,
    dndWrapper: (props) => <DndProvider backend={HTML5Backend} {...props} />,
  });
  return (
    <>
      <DndProvider backend={HTML5Backend}>
        <CommentsProvider users={{}} myUserId="1">
          <Plate
            plugins={plugins}
            initialValue={initialValue}
            editor={editor}
            onChange={() => {
              console.log(editor.children);
            }}
          >
            <FixedToolbar>
              <FixedToolbarButtons />
            </FixedToolbar>

            <Editor />

            <FloatingToolbar>
              <FloatingToolbarButtons />
            </FloatingToolbar>
            <MentionCombobox items={[]} />
            <CommentsPopover />
          </Plate>
        </CommentsProvider>
      </DndProvider>
      <button
        onClick={() => {
          console.log(html);
        }}
      >
        Click
      </button>
    </>
  );
};

export default RichTextEditor;

But at the moment I get an empty string for some reason

I think the problem is in creating the html, but I can't create this variable inside onChange or onClick.

Maybe someone has a ready-made code or knows how to solve the problem. I will be very grateful

0

There are 0 answers