javascriptreactjsdraftjs

Get caret position (line number) in draft.js


How do you get the caret position in draft.js? I guess you can get the block from the selectionstate and then get the block array and see at which position the block array is, but I'm not sure this is a reliable way, or even the best way.


Solution

  • Not sure if this is what you mean, but you can get the index of the current block like this:

    const currentBlockKey = editorState.getSelection().getStartKey()
    const currentBlockIndex = editorState.getCurrentContent().getBlockMap()
        .keySeq().findIndex(k => k === currentBlockKey)
    

    Here's a fiddle with a full example: https://jsfiddle.net/cczhL821/