Search code examples
javascriptdraftjs

DraftJS: how to move the focus (cursor) to some character on the right, programmatically?


I am inserting some text in the editor using this:

_insertText(text) {
    const { editorState, onChange } = this.props
    const newContentState = Modifier.insertText(
      editorState.getCurrentContent(),
      editorState.getSelection(),
      text
    )

    const newState = EditorState.createWithContent(newContentState)
    onChange(EditorState.acceptSelection(newState, editorState.getSelection()))
  }

But after the insertion, the cursor stay at the anchor position, at the insertion point. I would like to move it to the end of the inserted text, so I can continue editing without having to move the cursor manually.

Please help.


Solution

  • Fixed with this

    _insertText(text) {
        const { editorState, onChange } = this.props
        const newContentState = Modifier.insertText(
          editorState.getCurrentContent(),
          editorState.getSelection(),
          text
        )
    
        const newState = EditorState.createWithContent(newContentState)
        const nextOffSet = editorState.getSelection().getFocusOffset() + text.length
    
        const newSelection = editorState.getSelection().merge({
          focusOffset: nextOffSet,
          anchorOffset: nextOffSet
        })
    
        onChange(EditorState.acceptSelection(newState, newSelection))
      }
    

    If there is a better solution, please let me know.