HubSpot/draft-convert

Example from readme breaks links with ampersand, quote and other escaped characters

Opened this issue · 0 comments

soon commented

The following example:

import React from "react";
import { Editor, EditorState, Modifier } from "draft-js";
import "./styles.css";
import { convertToHTML } from "draft-convert";

export default function App() {
  const [editorState, setEditorState] = React.useState(
    EditorState.createEmpty()
  );

  const htmlFromDocs = convertToHTML({
    entityToHTML: (entity, originalText) => {
      if (entity.type === "LINK") {
        return <a href={entity.data.url}>{originalText}</a>;
      }
      return originalText;
    }
  })(editorState.getCurrentContent());

  const validHtml = convertToHTML({
    entityToHTML: (entity, originalText) => {
      if (entity.type === "LINK") {
        return <a href={entity.data.url} />;
      }
      return originalText;
    }
  })(editorState.getCurrentContent());

  const handleAddLinkClick = () => {
    const contentState = editorState.getCurrentContent();
    const contentStateWithEntity = contentState.createEntity(
      "LINK",
      "MUTABLE",
      { url: "https://google.com/" }
    );
    const entityKey = contentStateWithEntity.getLastCreatedEntityKey();
    const contentStateWithLink = Modifier.applyEntity(
      contentStateWithEntity,
      editorState.getSelection(),
      entityKey
    );
    const newEditorState = EditorState.push(
      editorState,
      contentStateWithLink,
      "apply-entity"
    );
    setEditorState(newEditorState);
  };

  return (
    <div>
      <button onClick={handleAddLinkClick}>Add Link</button>
      <Editor editorState={editorState} onChange={setEditorState} />
      <p>{htmlFromDocs}</p>
      <p>{validHtml}</p>
    </div>
  );
}

Uses return <a href={entity.data.url}>{originalText}</a>; as recommended in readme to serialize anchors. However this leads to double escaping (https://codesandbox.io/s/beautiful-flower-yy4o9):

Снимок экрана 2020-02-04 в 18 19 23

This can be fixed by omitting originalText and returning just <a href={entity.data.url} /> (I suppose library will automatically walk over children and add them).

TL;DR:

  1. Seems like example in readme is broken
  2. What is the correct way to serialize entities with nested content?