Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

draft.js: how to preserve paragraph breaks when pasting content?

Is there documentation that explains how to preserve paragraph breaks when content is pasted into draft.js? Other formating looks reasonable but all the paragraph blocks are collapsed into a single paragraph block when pasting.

like image 309
SteveB Avatar asked Aug 19 '16 21:08

SteveB


2 Answers

You can handle this using a prop for Editor.

handlePastedText = (text: string, html?: string, editorState: EditorState) => {
    const selection = editorState.getSelection();
    const pastedBlocks = ContentState.createFromText(text).blockMap;
    const newState = Modifier.replaceWithFragment(
        editorState.getCurrentContent(),
        editorState.getSelection(),
        pastedBlocks,
    );
    const newEditorState = EditorState.push(editorState, newState, "insert-fragment");
    this.handleChange(newEditorState);
    return "handled";
};

And then pass this as props in Editor. This will solve your problem.

like image 54
reetesh11 Avatar answered Sep 21 '22 18:09

reetesh11


Unfortunately, there is no public documentation of processing of pasted content. But since draft-js is open-sourced, reading the sources comes to the rescue.

Draft-js 0.9.1 and below

Just specify p as aliased element for unstyled block using blockRenderMap:

import { Map } from 'immutable';
import Editor from 'draft-js';

const customRenderMap = Map({
  unstyled: {
    element: 'div',
    // will be used in convertFromHTMLtoContentBlocks
    aliasedElements: ['p'],
  },
});

<Editor
  editorState={this.state.editorState}
  blockRenderMap={customRenderMap}
/>

Explanation:

When you paste content to draft-js, editOnPaste function gets invoked. Inside it draft determines that content you pasted is html (yes, when you copy-paste any text from text processors like MS Word, Google Docs or Apple Pages, it's actually html), and calls convertFromHTMLToContentBlocks().

convertFromHTMLToContentBlocks() in its turn uses blockRenderMap to determine how to split html to blocks.

Draft-js 0.10.0

div is aliased with p by default in [email protected]

like image 25
quotesBro Avatar answered Sep 19 '22 18:09

quotesBro