Search code examples
reactjsdomselectiondraftjs

Draft.js get selection or span for already styled elements


I'm using react-rte but am willing to extend it so let's talk about Draft-js.

I need to be able to "inline-style" a selection. Then on subsequent renders re-access that selection's dom.

So let's say I highlight a selection. Then I persist the document. Then I come back, reload the document, I need to be able get access to that highlighted section, but in the dom.

Basically on the side of the document I'm applying markers, outside of draft-js, and those markers need to line up with the highlighted part. So when I do the initial highlighting I can get the dom position from window.getSelection(), and i can place my marker. But the dom may change later and I won't be able to place my marker.

--edit--

So another use case is that I highlight a selection, and even in the same session, I need to change the color of the selection programatically so again I need to access the section of the document even if the cursor is not on that section.

--end edit--

So what I really need is something like an unique classname, id or even better a react ref for the new spans that are created when you do an inline style.

Please let me know if you need a better explanation.


Solution

  • The SelectionState records the selection, including start block, start offset, end block and end offset. It's not problem to save the selection in you code and apply to the editor later.

    So what I really need is something like an unique classname, id or even better a react ref for the new spans that are created when you do an inline style.

    So the id you want is a SelectionState, tell where the span is in draft-js editor.

    UPDATE

    You can find the block key which your inline styled text belongs to, in data-offset-key={blockkey}-xx-xx node attribute. The block key helps you find the node from SelectionState.getStartKey()/getEndKey(). Then find the span node by SelectionState.getStartOffset()/getEndOffset().