Last active
September 5, 2022 17:36
-
-
Save prenaudin/b10458683a24d02392916f70b20b037e to your computer and use it in GitHub Desktop.
Add checkboxes to your Draft.js editor - insertCheckbox.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Modifier, EditorState, Entity } from 'draft-js'; | |
export default function insertCheckbox(editorState) { | |
// Define the checkbox entity | |
const entityKey = Entity.create('CHECKBOX', 'IMMUTABLE', { checked: false }); | |
// Collapse selection | |
const selectionState = editorState.getSelection().merge({ | |
anchorOffset: selectionState.getFocusOffset(), | |
}); | |
// Insert the checkbox text | |
let newContent = Modifier.insertText( | |
editorState.getCurrentContent(), | |
selectionState, | |
'- [ ]' | |
); | |
// Set Checkbox Entity on this element | |
newContent = Modifier.applyEntity( | |
newContent, | |
newContent.getSelectionAfter(), | |
entityKey | |
); | |
// Push new EditorState | |
const newEditorState = EditorState.push( | |
editorState, | |
newContent, | |
'insert-checkbox' | |
); | |
return EditorState.forceSelection( | |
newEditorState, | |
newContent.getSelectionAfter() | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment