How retrieve text from draftjs
Asked Answered
B

4

23

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?

Brownout answered 3/8, 2018 at 4:53 Comment(0)
A
28

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');
Allerie answered 3/8, 2018 at 5:29 Comment(0)
O
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

Overstep answered 23/5, 2019 at 13:9 Comment(4)
Can you explain why you'd use the "start of heading" char? Also, the docs say it'll use a LF, not "single space" (draftjs.org/docs/api-reference-content-state/#getplaintext)Carbide
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?Determined
It's been a while, but I remember that in order to change value you should use this: draftjs.org/docs/api-reference-editor-state#pushOverstep
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.7Sieber
A
28

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');
Allerie answered 3/8, 2018 at 5:29 Comment(0)
C
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";
      }
    }
Confectionary answered 21/11, 2019 at 0:35 Comment(0)
H
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;
  }, "");
};```
Homogeneous answered 10/6, 2020 at 1:3 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.