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?
Draft. js comes with convertToRaw method that takes in a ContentState object and returns the given ContentState as a raw javascript object. This object can then be stored to a database or wherever you need to store your application's data.
ContentBlock is an Immutable Record that represents the full state of a single block of editor content, including: Plain text contents of the block. Type, e.g. paragraph, header, list item. Entity, inline style, and depth information.
An entity is an object that represents metadata for a range of text within a Draft editor. It has three properties: type: A string that indicates what kind of entity it is, e.g. 'LINK' , 'MENTION' , 'PHOTO' .
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');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With