Sarath Kumar
Sarath Kumar

Reputation: 1146

Set EditorState without the application state in Draft js

I want to update the Draft js Editor with some initial content. I know we can change EditorState using component state.

import React from 'react';
import ReactDOM from 'react-dom';
import {Editor, EditorState} from 'draft-js';

class MyEditor extends React.Component {
  constructor(props) {
    super(props);
    this.state = {editorState: EditorState.createEmpty()};
    this.onChange = (editorState) => this.setState({editorState});
  }
  render() {
    return (
        <Editor editorState={this.state.editorState} onChange={this.onChange} />
    );
  }
}

Whenever I tried to change something in the Editor it's re rendering. This is causing some performance issue. Is there anyway I can set or change the Editor's state without changing the state. Something similar to this

EditorState.set(editorState); //here editorState is new editor state;

Any idea how to achieve?

Upvotes: 0

Views: 2032

Answers (1)

Sarath Kumar
Sarath Kumar

Reputation: 1146

After the two days of struggle, I found one useful wysiwyg editor built on top of Draft.js with cool features. It has all the features given by Draft.js. We can load existing content using Editor's refs.

import {EditorState, convertFromRaw} from 'draft-js';
import { Editor } from 'react-draft-wysiwyg';


class myEditor extends Component {

   componentDidMount(){
       //I have stored rawContent in  database
       let rawContent={"blocks":[{"key":"3ge2q","text":"Hello World!;","type":"header-three","depth":0,"inlineStyleRanges":[],"entityRanges":[],"data":{}}],"entityMap":{}};
       //Convert Raw to contentState
       let content=convertFromRaw(rawContent);
       let editorState=EditorState.createWithContent(content);
       this.refs.editor.editor.update(editorState); //Update the editor with updated content.
   }

    render(){
      <Editor
         ref="editor"
         wrapperClassName="demo-wrapper"
         editorClassName="template-editor"
         spellCheck={true}
         placeholder="Type something"
         onEditorStateChange={this.onEditorStateChange.bind(this)}
     />
  }
}

Upvotes: 1

Related Questions