Get caret position (line number) in draft.js

4.7k views Asked by At

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.

2

There are 2 answers

1
tobiasandersen On BEST ANSWER

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/

1
chenjiahe On

you can get the caret positon like below

editorState.getSelection().getFocusOffset()