Draft-js: How to intercept keypresses

Created on 11 Jul 2016  路  5Comments  路  Source: facebook/draft-js

Is there a way to intercept text key presses? I don't meant command keys but regular input. Say I wanted every 'a' press to be turned into 'b'?

My real goal is to capture the enter key and insert new lines instead of splitting blocks, but only in certain cases.

If the current behavior is a bug, please provide the steps to reproduce and if possible a minimal demo of the problem via https://jsfiddle.net or similar.

What is the expected behavior?

Which versions of Draft.js, and which browser / OS are affected by this issue? Did this work in previous versions of Draft.js?

Most helpful comment

Ah. Somehow I had missed 'handleReturn'. I want to have return add a newline inside of code blocks, but elsewhere do a normal split block. Here is the handleReturn function that does it:

    handleReturn(e) {
        var selection = this.state.editorState.getSelection();
        var content = this.state.editorState.getCurrentContent();
        var block = content.getBlockForKey(selection.getAnchorKey());
        if(block.type == 'code-block') {
            this.onChange(RichUtils.insertSoftNewline(this.state.editorState));
            return true;
        }
        return false;
    }

All 5 comments

There's a handleReturn event and you can return false to defer to Draft's handler.
RichUtils has insertSoftNewline (and in that case you should probably return true).

@joshmarinacci you can use handleBeforeInput but it only gets called for _input_ (not deletions such as cut/delete/backspace)

The change I'm proposing in https://github.com/facebook/draft-js/pull/453 should handle all changes. If you think that will help, please comment there!

Ah. Somehow I had missed 'handleReturn'. I want to have return add a newline inside of code blocks, but elsewhere do a normal split block. Here is the handleReturn function that does it:

    handleReturn(e) {
        var selection = this.state.editorState.getSelection();
        var content = this.state.editorState.getCurrentContent();
        var block = content.getBlockForKey(selection.getAnchorKey());
        if(block.type == 'code-block') {
            this.onChange(RichUtils.insertSoftNewline(this.state.editorState));
            return true;
        }
        return false;
    }

thanks for the code @joshmarinacci !

Looks like this has been resolved, so I'm closing this out. If that's not the case, please reopen.

Was this page helpful?
0 / 5 - 0 ratings