DraftJS: Reset blockType after return
Asked Answered
Z

1

8

I am currently building an editor like the one that is used on medium.com. For each unstyled block, I render a custom component that holds edit buttons to change the block type of that section.

However, when I for example change the section to a header-one and hit the return button the new block is also a header-one block. I like to see that the new block is unstyled instead of the same type of the previous block.

Any ideas on how to do this?

Zebulun answered 23/3, 2018 at 15:49 Comment(1)
You just saved me so much time. Thank you!Cordy
H
0

After some more searching and trying I found the solution myself! It appears that the best way to do this is by inserting a new block when the split-block keyCommand is fired.

For example:

createEmptyBlock(editorState: Draft.EditorState) {
    const newBlock = new Draft.ContentBlock({
        key: Draft.genKey(),
        type: "unstyled",
        text: "",
        characterList: Immutable.List()
    })

    const contentState = editorState.getCurrentContent()
    const newBlockMap = contentState.getBlockMap().set(newBlock.getKey(), newBlock)

    return Draft.EditorState.push(
        editorState,
        Draft.ContentState
            .createFromBlockArray(newBlockMap.toArray())
            .set('selectionAfter', contentState.getSelectionAfter().merge({
                anchorKey: newBlock.getKey(),
                anchorOffset: 0,
                focusKey: newBlock.getKey(),
                focusOffset: 0,
                isBackward: false,
            })) as Draft.ContentState,
        "split-block"
    )
}

This answer was posted as an edit to the question DraftJS: Reset blockType after return by the OP n9iels under CC BY-SA 3.0.

Hosiery answered 2/12, 2022 at 12:31 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.