Search code examples
reactjswysiwygdraftjs

Adding Entity into its own block in DraftJS


So I'm trying to create a fairly simple WYSIWYG BBCode editor for my project as an opportunity to wrap my mind around DraftJS. I've been following some tutorials and also using react-rte as an example (since it has 99% of the functionality I need and looks relatively simple to understand).

The problem I've stumped on is that react-rte inserts image entities inline (it adds a space in the current selection and then ties an entry to that space) like this:

const addEntity = (editorState, type, mutability = 'MUTABLE', data = {}) => {
    let currentContent = editorState.getCurrentContent();
    let selection = editorState.getSelection();
    currentContent = currentContent.createEntity(type, mutability, data);
    let entityKey = currentContent.getLastCreatedEntityKey();
    return Modifier.insertText(currentContent, selection, ' ', null, entityKey);
}

I want each image (and video alike) to be in its own separate block and make it so nothing else can be written to that block. I have found an example of the behavior I'm after in megadraft, but I have been unable to work my way through its code to find the correct implementation.


Solution

  • Found the solution after many hours of trial and error (and lots of manuals).

    const addAtomic = (editorState, type, mutability = 'MUTABLE', data = {}) => {
        let currentContent = editorState.getCurrentContent();
        let selection = editorState.getSelection();
        currentContent = currentContent.createEntity(type, mutability, data);
        let entityKey = currentContent.getLastCreatedEntityKey();
        const newState = EditorState.set(editorState, { currentContent: currentContent })
        return AtomicBlockUtils.insertAtomicBlock(newState, entityKey, ' ')
    }