EzDev.org

draft-js

draft-js - A React framework for building text editors. Draft.js | Rich Text Editor Framework for React


draftjs how to initiate an editor with content

Stumbled on this cool text editor, draft.js by facebook. I try to follow the example in github but I want to create an editor with content instead an empty editor.

var EditorState = Draft.EditorState;

var RichEditor = React.createClass({
   getInitialState(){
      return {editorState: EditorState.createWithContent("Hello")}
      //the example use this code to createEmpty editor
     // return ({editorState: EditorState.createEmpty()})
   }
});

run it, but I get error saying that "Uncaught TypeError: contentState.getBlockMap is not a function"


Source: (StackOverflow)

Draft js. Persist EditorContent to database

I'm trying to persist draft-js's EditorContent to database then read and recreate the EditorContent object again. But EditorContent.getPlainText() strips away rich text content. I don't know how else to do it.

How do I properly persist EditorContent?


Source: (StackOverflow)

Draft.js editor is empty

How to test if the content of draftjs editor is empty?

The only idea that I have now is an object comparison against the object returned from this function : EditorState.createEmpty().getCurrentContent()


Source: (StackOverflow)

How to limit Max Length of Draft js

How to limit max characters in draft js?

I can get length of the state like that, but how to stop updating component?

var length = editorState.getCurrentContent().getPlainText('').length;

Source: (StackOverflow)

Draftjs styling in React

I want to use draft.js in my project. It has its own css which I also need to import. In the documentation it is said:

This CSS should be included when rendering the editor, as these styles set defaults for text alignment, spacing, and other important features.

  1. How do I include the Draft.css while rendering the component? Do I include it in my main index.html?
  2. Also how to give an id to the editor so that I can style it (eg. border, padding, min-height, etc)

Source: (StackOverflow)

Create "Karaoke" Type Functionality in DraftJS

I am attempting to implement a DraftJS editor that highlights words in a transcription while its recorded audio is playing (kind of like karaoke).

I receive the data in this format:

[
  {
    transcript: "This is the first block",
    timestamps: [0, 1, 2.5, 3.2, 4.1, 5],
  },
  {
    transcript: "This is the second block. Let's sync the audio with the words",
    timestamps: [6, 7, 8.2, 9, 10, 11.3, 12, 13, 14, 15, 16, 17.2],
  },
  ...
]

I then map this received data to ContentBlocks and initialize the editor's ContentState with them by using ContentState.createFromBlockArray(blocks)

It seems like the "DraftJS" way of storing the timestamp metadata would be to create an Entity for each word with its respective timestamp, and then scan through the currentContent as the audio plays and highlight entities up until the current elapsed time. But I am not sure if this is the right way to do this, as it doesn't seem performant for large transcriptions.

Note: the transcript needs to remain editable while maintaining this karaoke functionality

Any help or discussion is appreciated!


Source: (StackOverflow)

draft.js: how to preserve paragraph breaks when pasting content?

Is there documentation that explains how to preserve paragraph breaks when content is pasted into draft.js? Other formating looks reasonable but all the paragraph blocks are collapsed into a single paragraph block when pasting.


Source: (StackOverflow)

I can't get the html output from draft-js?

I've been playing around with draft-js by Facebook, but I can't actually figure out how to get the html output of the editor. The console.log in the following example outputs some _map properties, but they don't seem to contain my actual content?

class ContentContainer extends React.Component {
      constructor(props) {
        super(props);
        this.state = {
          value: '',
          editorState: EditorState.createEmpty()
        };
        this.onChange = (editorState) => this.setState({editorState});
        this.createContent = this.createContent.bind(this);
      }

      createContent() {
        console.log(this.state.editorState.getCurrentContent());
      }

      render() {
        const {editorState} = this.state;
        const { content } = this.props;
        return (
          <Template>
            <br /><br /><br />
            <ContentList content={content} />
            <div className="content__editor">
              <Editor editorState={editorState} onChange={this.onChange} ref="content"/>
            </div>
            <FormButton text="Create" onClick={this.createContent.bind(this)} />
          </Template>
        );
      }
    }

Source: (StackOverflow)

Detect blur aka losing focus of a Draft.js editor

Is there a "correct way" to detect if I lose focus of a Draft.js editor?

The use case is, that I want "quit editor mode" if the user clicks elsewhere which means that I toggle the readOnly prop of the editor. How can I do this ideally and is it a good idea to do that (do you see problems with that)?


Source: (StackOverflow)

How to clear input field in Draft-js

None of the demos that I've seen for Draft-js (by Facebook, built on React) show how to clear the input field after submit. For example, see this code pen linked to from awesome-draft-js where the value you submit remains in the input field after submit. There's also no function in the api that seems designed to do it. What I've done to achieve that is to create a new empty state on button submission like this

onSubmit(){
this.setState({
   editorState: EditorState.createEmpty(),
})
}

However, since I create an empty state in the constructor when the editor is loaded like this

  this.state = {
    editorState: EditorState.createEmpty(),
  };

I'm worried that I might not be doing it in the right way i.e. the previous state object might become a memory leak. Question: what is the intended way to reset the state in the above situation (i.e. button submit)


Source: (StackOverflow)

Draftjs mention plugin with browserify

I tried to get the mention plugin in draft-js get working with Browserify. This is because of the fact that our application is build with Browserify.

It's about this plugin: https://www.draft-js-plugins.com/plugin/mention

In the examples they are using Webpack, and they use imports.

I use require. So an example of my code is:

var React       = require('react'),
    Draft       = require('draft-js'),
    Immutable   = require('immutable'),
    Editor      = require('draft-js-plugins-editor'),
    Mention     = require('draft-js-mention-plugin');

var mentionPlugin = Mention.createMentionPlugin();
var MentionSuggestions = mentionPlugin.MentionSuggestions;
var plugins = [mentionPlugin];

var Editor = React.createClass({
    // Code
});

I don't use ES6 notation. Does anybody know what I'm doing wrong?


Source: (StackOverflow)

Replace content block

guys! Please help.

What I want: When starting from a new line a user types an URL and presses Enter I want to remove the block containing the URL and replace it with a custom Entity. Much like the Media example from the docs, but without the Add image button.

What I tried: (just a rough draft)

var mediaBlockRenderer = function(block) {
    if (block.getType() === 'atomic') {
        return {
            component: TestComponent,
            editable: false
        };
    }
    return null;
};

var TestComponent = function() {
    return <div className="test-component">TEST COMPONENT</div>;
};

onChange: function(editorState) {
        var currentKey = editorState.getSelection().getStartKey();
        var content = editorState.getCurrentContent();
        var selection = content.getSelectionBefore();
        var beforeKey = content.getKeyBefore(currentKey);
        var block = content.getBlockForKey(beforeKey);

        if (block && block.getText() === 'test') {
            console.log(block.getText());
            var len = block.getCharacterList().size;

            var newSelection = selection.merge({
                anchorOffset: 0,
                focusOffset: len
            });

            var newContent = Modifier.removeRange(content, newSelection, 'backward');
            editorState = EditorState.push(editorState, newContent, 'insert');
            var key = Entity.create('media', 'IMMUTABLE');
            editorState = AtomicBlockUtils.insertAtomicBlock(
                editorState,
                key,
                ' '
            );
            //editorState = EditorState.forceSelection(editorState, newContent.getSelectionBefore());

        }

        this.setState({
            editorState: editorState
        })
    }

It almost does what I want, but the inserted block can't be deleted by pressing backspace, the cursor just jumps to the top right corner.

My question: What is the recommended way of replacing blocks? How do you remove a block? And why my inserted block just won't get deleted?

Thanks!


Source: (StackOverflow)

Callback is not working in ajax request?

I am trying to build a contentEditor with draft js. Exactly the feature is Extract the data from url like Facebook. But I am stuck with this part. Callback is not working.

First I wrapped my state with compositeDecorator Like this

constructor(props) {
    super(props);
    const compositeDecorator = new CompositeDecorator([
        .... {
            strategy: linkStrategy,
            component: decorateComponentWithProps(linkComp, {
                passit
            })
        }
        ....
    ]);
}
// This is my strategy
function linkStrategy(contentBlock, callback, contentState) {
    findLinkInText(LINK_REGEX, contentBlock, callback)
}

function findLinkInText(regex, contentBlock, callback) {
    const text = contentBlock.getText();
    let matchArr, start;
    if ((matchArr = regex.exec(text)) !== null) {
        start = matchArr.index;
        let URL = matchArr[0];
        console.log(URL);
        axios.post('/url', {
            url: URL
        }).then(response => {
            passit = response.data
            //not working
            callback(start, start + URL.length)
        })
        //working
        callback(start, start + URL.length)
    }
}

If the callback won't work, the component will not render.. I don't know this is a basic javascript problem. But the thing is I want to fetch the url data from my server and I have to pass the data via props to my component and render it.

UPDATE FOR THE ANSWER

function findLinkInText(regex, contentBlock, callback) {
    const text = contentBlock.getText();
    let matchArr, start;
    if ((matchArr = regex.exec(text)) !== null) {
        start = matchArr.index;
        let url = matchArr[0];
        axios.post('/url', {
            url: URL
        }).then(response => {
            passit = response.data
            handleWithAxiosCallBack(start, start + matchArr[0].length, callback)
        }).catch(err => console.log(err))
    }
}


function handleWithAxiosCallBack(start, startLength, callback) {
    console.log(callback); //Spits out the function But Not working
    callback(start, startLength)
}

Source: (StackOverflow)

Best performance method to check if contentState changed in DraftJS, or just editorState

I'm trying to have a function run only when the contentState itself has changed, not just the editorState.

My idea right now would be to store the old contentState as a string and compare it to the new contentState as a string, but this seems awfully wasteful to be converting states to strings and comparing them. Is there a better way?


Source: (StackOverflow)

Combine draft-js with redux-form

I have a form with 2 usual inputs where i can use this common approach:

<input {...title} />

And also i have a draftJS editor in the form. I need to convert draftJS content to HTML (via draft-js-export-html) on submit, and load html to it on component mount process. How to combine it with redux-form?


Source: (StackOverflow)