How to go to next line after pressing ctrl + return while in code block in draftjs

40 views Asked by At

Hi friends i am struggling with draftjs i am using reactjs with draftjs and draftjs-to-code to build richfull text editor i want to implement writing code in text editor for that i am using draftjs-to-code the good thing is that it go to new line after pressing return and not leave code-block but i want after pressing ctrl + return it go to next line and leave the code-block and user able to write simple text

i want after user pressing ctrl + return cursor moves to next line and user able to write simple text

1

There are 1 answers

0
João Gervas On

It sounds like you want to implement a feature in your Draft.js editor where pressing Ctrl + Return moves the cursor to the next line and leaves the code-block.

You can create a custom key binding function that checks if Ctrl + Return was pressed. If it was, you can then manipulate the editor state to create a new block of type ‘unstyled’, which will allow the user to write simple text1.

Here’s a sample implementation:

import { EditorState, Modifier, getDefaultKeyBinding } from 'draft-js';

function keyBindingFn(event) {
  if (event.ctrlKey && event.keyCode === 13) {
    return 'ctrl+return';
  }
  return getDefaultKeyBinding(event);
}

function handleKeyCommand(command, editorState) {
  if (command === 'ctrl+return') {
    const selection = editorState.getSelection();
    const contentState = editorState.getCurrentContent();
    const newContentState = Modifier.splitBlock(contentState, selection);
    const newEditorState = EditorState.push(editorState, newContentState, 'split-block');
    this.setState({ editorState: newEditorState });
    return 'handled';
  }
  return 'not-handled';
}

// In your Editor component
<Editor
  editorState={this.state.editorState}
  handleKeyCommand={handleKeyCommand}
  keyBindingFn={keyBindingFn}
  onChange={this.onChange}
/>

In this code, keyBindingFn checks if Ctrl + Return was pressed and if so, returns a command string ‘ctrl+return’handleKeyCommand checks if the command is ‘ctrl+return’ and if so, splits the block at the current cursor position, creating a new ‘unstyled’ block1.

Remember to replace this.state.editorState and this.onChange with your own editor state and change handler.