What's the best way to add an empty unstyled block, let's say last, to a Draft.js editor without changing the SelectionState?
Add empty block to Draft.js without moving selection
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())
)
}
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) –
Mesoglea
When I use this, the block gets appended to the end. –
Used
@AdamLibuša The solution to your issue is in this GitHub comment and the explanation is in this Stack Overflow answer. –
Tirewoman
© 2022 - 2024 — McMap. All rights reserved.