Displaying the output of react-draft-wysiwyg to users as a html

44 views Asked by At

I been attempting to create a blog post web app using reactjs and i am using react-draft-wysiwyg library i been temporary storing the editor content to localstorage but plan to store it on firebase or mongoDB so here is my code.

Storing the content

import { Editor } from "react-draft-wysiwyg";
import { EditorState, convertToRaw, convertFromRaw } from "draft-js";
import "react-draft-wysiwyg/dist/react-draft-wysiwyg.css";

    EditorState.createEmpty()
  );

  const saveContent = (content) => {
    window.localStorage.setItem(
      "content",
      JSON.stringify(convertToRaw(content))
    );
  };

  useEffect(() => {
    const content = window.localStorage.getItem("content");
    if (content)
      setEditorState(
        EditorState.createWithContent(convertFromRaw(JSON.parse(content)))
      );
  }, []);

  const updateTextDescription = async (state) => {
    const contentState = state.getCurrentContent();
    saveContent(contentState);
    await setEditorState(state);

    const data = convertToRaw(editorState.getCurrentContent());
    console.log(data);
  };

 <Editor
  editorState={editorState}
  toolbarClassName="toolbarClassName"
   wrapperClassName="border border-gray-300"
  editorClassName="p-2"
  onEditorStateChange={updateTextDescription}
  />

Retrieving the content i read that you need to use draftjs-to-html library

import { convertFromRaw } from "draft-js";
import draftToHtml from "draftjs-to-html";

  const [htmlContent, setHtmlContent] = useState("");

  useEffect(() => {
    try {
      const _content = window.localStorage.getItem("content");
      
      if (_content) {
        const convertedState = convertFromRaw(JSON.parse(_content));

        const html = draftToHtml(convertedState);
        console.log(html);
        setHtmlContent(html);
      } else {
        console.error("No content found in localStorage.");
      }
    } catch (error) {
      console.error("Error parsing Draft.js content:", error);
    }
  }, []);

<div dangerouslySetInnerHTML={{ __html: htmlContent }} />

Ok so the problem is the output of console.log(html) is an empty string but console.log(convertedState) is an object.

0

There are 0 answers