What's the best way to add an empty unstyled block, let's say last, to a Draft.js editor without changing the SelectionState?
Asked
Active
Viewed 8,250 times
1 Answers
17
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())
)
}

tobiasandersen
- 8,480
- 3
- 28
- 39
-
I am getting an error while trying this react-dom.development.js?46fb5f3:610 Uncaught TypeError: Cannot read property 'get' of undefined at getUpdatedSelectionState (getUpdatedSelectionState.js?93c9c7b:41) at getDraftEditorSelectionWithNodes (getDraftEditorSelectionWithNodes.js?93c9c7b:90) at getDraftEditorSelection (getDraftEditorSelection.js?93bb2c4:35) at editOnSelect (editOnSelect.js?93bb2c4:33) at DraftEditor.react.js?1037aeb:218 at HTMLUnknownElement.callCallback (react-dom.development.js?46fb5f3:542) – divyenduz Mar 13 '18 at 12:56
-
2When I use this, the block gets appended to the end. – Adam Libuša Nov 08 '18 at 09:40
-
1@AdamLibuša The solution to your issue is in [this GitHub comment](https://github.com/facebook/draft-js/issues/2325#issuecomment-652127067) and the explanation is in [this Stack Overflow answer](https://stackoverflow.com/a/43513374/7929984). – Nikhil Sinha Jul 07 '20 at 16:42