Skip to content

Instantly share code, notes, and snippets.

@prenaudin
Last active September 5, 2022 17:36
Show Gist options
  • Save prenaudin/ed25fd6c8debb6b82bd39002df6a964f to your computer and use it in GitHub Desktop.
Save prenaudin/ed25fd6c8debb6b82bd39002df6a964f to your computer and use it in GitHub Desktop.
Add checkboxes to your Draft.js editor - Editor.react.js
import React from 'react';
import { Editor, KeyBindingUtil, getDefaultKeyBinding } from 'draft-js';
import keycode from 'keycode';
import insertCheckbox from 'modifiers/insertCheckbox';
const { hasCommandModifier } = KeyBindingUtil;
function customKeyBindingFn(e) {
if (hasCommandModifier(e) && e.shiftKey && keycode(e) === 'c') {
return 'insert-checkbox';
}
return getDefaultKeyBinding(e);
}
export default class Editor extends React.Component {
handleKeyCommand(command) {
let newEditorState = null;
switch (command) {
case 'insert-checkbox':
newEditorState = insertCheckbox(this.props.editorState);
break;
default:
newEditorState = RichUtils.handleKeyCommand(this.props.editorState, command);
}
this.props.onEditorStateChange(newEditorState);
}
render() {
return (
<Editor
editorState={this.props.editorState}
handleKeyCommand={this.handleKeyCommand.bind(this)}
keyBindingFn={customKeyBindingFn}
onChange={this.props.onEditorStateChange}
/>
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment