Search code examples
reactjsdraftjs

Add empty block to Draft.js without moving selection


What's the best way to add an empty unstyled block, let's say last, to a Draft.js editor without changing the SelectionState?


Solution

  • This is what I ended up doing:

    import { List } from 'immutable'
    import {
      EditorState,
      ContentState,
      ContentBlock,
      genKey
    } from 'draft-js'
    
    const addEmptyBlock = (editorState) => {
      const newBlock = new ContentBlock({
        key: genKey(),
        type: 'unstyled',
        text: '',
        characterList: List()
      })
    
      const contentState = editorState.getCurrentContent()
      const newBlockMap = contentState.getBlockMap().set(newBlock.key, newBlock)
    
      return EditorState.push(
        editorState,
        ContentState
          .createFromBlockArray(newBlockMap.toArray())
          .set('selectionBefore', contentState.getSelectionBefore())
          .set('selectionAfter', contentState.getSelectionAfter())
      )
    }