Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handling tab for lists in Draft.js

Tags:

draftjs

I have a wrapper around the Editor provided by Draft.js, and I would like to get the tab/shift-tab keys working like they should for the UL and OL. I have the following methods defined:

  _onChange(editorState) {
    this.setState({editorState});
    if (this.props.onChange) {
      this.props.onChange(
        new CustomEvent('chimpeditor_update',
          {
            detail: stateToHTML(editorState.getCurrentContent())
          })
      );
    }
  }

  _onTab(event) {
    console.log('onTab');
    this._onChange(RichUtils.onTab(event, this.state.editorState, 6));
  }

Here I have a method, _onTab, which is connected to the Editor.onTab, where I call RichUtil.onTab(), which I assume returns the updated EditorState, which I then pass to a generic method that updates the EditorState and calls some callbacks. But, when I hit tab or shift-tab, nothing happens at all.

like image 916
CodeChimp Avatar asked Jun 03 '16 00:06

CodeChimp


2 Answers

So this came up while implementing with React Hooks, and a google search had this answer as the #2 result.

I believe the code OP has is correct, and I was seeing "nothing happening" as well. The problem turned out to be not including the Draft.css styles.

import 'draft-js/dist/Draft.css'

like image 78
David Avatar answered Oct 31 '22 14:10

David


import { Editor, RichUtils, getDefaultKeyBinding } from 'draft-js'


handleEditorChange = editorState => this.setState({ editorState })

handleKeyBindings = e => {
  const { editorState } = this.state
  if (e.keyCode === 9) {
    const newEditorState = RichUtils.onTab(e, editorState, 6 /* maxDepth */)
    if (newEditorState !== editorState) {
       this.handleEditorChange(newEditorState)
    }

    return
  }

  return getDefaultKeyBinding(e)
}

render() {
  return <Editor onTab={this.handleKeyBindings} />
}
like image 43
user10693896 Avatar answered Oct 31 '22 14:10

user10693896