Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
soon opened this issue Feb 4, 2020 · 0 comments

Comments

@soon
Copy link

soon commented Feb 4, 2020

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?
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

No branches or pull requests

1 participant