Handling tab for lists in Draft.js
Asked Answered
I

3

6

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.

Intoxicative answered 3/6, 2016 at 0:7 Comment(1)
this seems like a fine implementation, works on my machine. Do you see the console.log output? if not you did not bind your calls properly. Let me know how the file looksMalacology
C
4

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'

Cuisse answered 4/9, 2019 at 4:17 Comment(0)
C
3
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} />
}
Cocklebur answered 23/11, 2018 at 4:53 Comment(1)
This doesn't seems to answer the OP. A good answer would give the OP an explanation of why his code doesn't work and then propose a change with a code example.Spidery
T
0

The following example will inject \t into the current location, and update the state accordingly.

function custKeyBindingFn(event) {
if (event.keyCode === 9) {
  let newContentState = Modifier.replaceText(
    editorState.getCurrentContent(),
    editorState.getSelection(),
    '\t'
  );

  setEditorState(EditorState.push(editorState, newContentState, 'insert-characters'));

  event.preventDefault(); // For good measure. (?)
  return null;
}
return getDefaultKeyBinding(event);
}
Transmogrify answered 23/11, 2022 at 15:38 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.