Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 370
tobiasandersen Avatar asked Sep 16 '16 11:09

tobiasandersen


1 Answers

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())
  )
}
like image 128
tobiasandersen Avatar answered Nov 14 '22 19:11

tobiasandersen