Skip to content

Instantly share code, notes, and snippets.

@prenaudin
Last active September 5, 2022 17:36
Show Gist options
  • Save prenaudin/b10458683a24d02392916f70b20b037e to your computer and use it in GitHub Desktop.
Save prenaudin/b10458683a24d02392916f70b20b037e to your computer and use it in GitHub Desktop.
Add checkboxes to your Draft.js editor - insertCheckbox.js
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