How retrieve text from draftjs
Piyush Zalani answer is almost correct but the final join causes extra new lines to be appended if there is a block with nothing in it.
Here is a slightly modified version which correctly accounts for blocks that have only line breaks:
const blocks = convertToRaw(editorState.getCurrentContent()).blocks;
const mappedBlocks = blocks.map(
block => (!block.text.trim() && "\n") || block.text
);
let newText = "";
for (let i = 0; i < mappedBlocks.length; i++) {
const block = mappedBlocks[i];
// handle last block
if (i === mappedBlocks.length - 1) {
newText += block;
} else {
// otherwise we join with \n, except if the block is already a \n
if (block === "\n") newText += block;
else newText += block + "\n";
}
}
The best way to retrieve text is by just using
editorState.getCurrentContent().getPlainText('\u0001')
Note that the function getPlainText
will always create a single space between blocks, so you need to send \u0001
as a parameter
You can make use of convertToRaw function of DraftJS something like following to get the text with break lines:
import {
convertToRaw,
} from 'draft-js';
const blocks = convertToRaw(editorState.getCurrentContent()).blocks;
const value = blocks.map(block => (!block.text.trim() && '\n') || block.text).join('\n');