22

I'm trying to edit a text and then retrieve it and update the database on the server side

this is the code I'm using

constructor(props,context){
    super(props,context);
    this.handleOnClick = this.handleOnClick.bind(this);

    const processedHTML = DraftPasteProcessor.processHTML(this.props.rule.description.replace(/\n/g, "<br />"));
    const contentState = ContentState.createFromBlockArray(processedHTML); 
    var editorState = EditorState.createWithContent(contentState);
    var editorState = EditorState.moveFocusToEnd(editorState);
    this.state = {editorState: editorState};
    this.onChange = (editorState) => this.setState({editorState});
}



handleOnClick(event) {
   var text = this.state.editorState.getCurrentContent().getBlocksAsArray();
   var finalText;
   text.map((item) => {
   finalText = item.getText() + finalText});
   console.log(finalText)

  render(){

    return(
    <div>
    <Col smOffset={2} mdOffset={1}>
    <PageHeader>
        {this.props.rule.title}
    </PageHeader>
    <Editor
      editorState={this.state.editorState}
      onChange={this.onChange}
    />
    </Col>

     <Col smOffset={2} mdOffset={1}>
    <Button onClick = {this.handleOnClick()}>Update rule</Button>
    </Col>
    </div>
    );

}

But I'm having a problem, draftJs returns the text without the \n so I'd save the text badly formatted, is there any way to get the text with breaklines?

JoseCarlosPB
  • 933
  • 2
  • 14
  • 29

4 Answers4

40

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

Breno Prata
  • 712
  • 5
  • 10
  • 2
    Can you explain why you'd use the "start of heading" char? Also, the docs say it'll use a LF, not "single space" (https://draftjs.org/docs/api-reference-content-state/#getplaintext) – mpen Jun 10 '20 at 01:20
  • Is there a way I can update the plain text value of the same node from which I'm reading text using the method you suggested? – Deepak Singh Mar 02 '21 at 11:07
  • It's been a while, but I remember that in order to change value you should use this: https://draftjs.org/docs/api-reference-editor-state#push – Breno Prata Mar 03 '21 at 12:27
  • 3
    Just editorState.getCurrentContent().getPlainText() works fine, if you pass '\u0001' then you get raw text without line breaks. At least that how it works for version 0.11.7 – Vano Apr 30 '21 at 06:07
26

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');
Ramiz Ansari
  • 524
  • 1
  • 6
  • 16
Piyush Zalani
  • 3,686
  • 1
  • 13
  • 29
2

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";
      }
    }
justswim
  • 944
  • 9
  • 8
0
  const { blocks } = convertToRaw(editorState.getCurrentContent());
  const mappedBlocks = blocks.map(
    block => (!block.text.trim() && "\n") || block.text,
  );

  return mappedBlocks.reduce((acc, block) => {
    let returned = acc;
    if (block === "\n") returned += block;
    else returned += `${block}\n`;
    return returned;
  }, "");
};```