Draftjs: link not working, renders as normal text

Viewed 1542

I'm trying to add links to my draftjs editor. I first select the text i want to add a link to, then click on a button that asks for the URL. Much like stackoverflow's own editor.

I am rendering the editor output to markdown, and I can see that a link has been added, as markdown shows the typical syntax [selected text](added hyperlink) , but in the editor itself, the selected text to which I am adding the hyperlink, remains looking like normal text.

CodeSandbox: https://codesandbox.io/s/github/Suedo/MobX2020/tree/draftjs-test

Can someone help me fix it please?

Here is the handler method in charge of adding links:

  const addLink = () => {
    console.log('in addlink');
    const selectionState = editorState.getSelection();
    const link = window.prompt('Paste your link: ');
    if (!link) {
      // onEditorChange(RichUtils.toggleLink(editorState, selectionState, null));
      return;
    }
    const contentState = editorState.getCurrentContent();
    const contentStateWithEntity = contentState.createEntity('LINK', 'MUTABLE', {
      url: link,
    });

    const entityKey = contentStateWithEntity.getLastCreatedEntityKey();
    const contentStateWithLink = Modifier.applyEntity(contentStateWithEntity, selectionState, entityKey);
    const newEditorState = EditorState.set(editorState, {
      currentContent: contentStateWithLink,
    });

    onEditorChange(RichUtils.toggleLink(newEditorState, newEditorState.getSelection(), entityKey));
    return;
  };

Where my onEditorChange is a simple method that sets the editorState like so:

  const onEditorChange = (newState: any) => {
    setEditorState((editorState) => newState);
  };
0 Answers
Related