5

I'm creating a rich text editor using draftjs. Here is the minimal codesandbox so you have an idea of what the issue is.

So I have an helper function getCurrentTextSelection that return me the text that I'm selecting:

const getCurrentTextSelection = (editorState: EditorState): string => {
  const selectionState = editorState.getSelection();
  const anchorKey = selectionState.getAnchorKey();
  const currentContent = editorState.getCurrentContent();
  const currentContentBlock = currentContent.getBlockForKey(anchorKey);
  const start = selectionState.getStartOffset();
  const end = selectionState.getEndOffset();
  const selectedText = currentContentBlock.getText().slice(start, end);

  return selectedText;
};

When I click outside the TextEditor, the focus is lost so the text isn't selected (but stay the selected one for the editorState).

Is there a programmatic way to reselect this text using the editorState? So that when you click the Select text again button, the text in the TextEditor is selected.

johannchopin
  • 13,720
  • 10
  • 55
  • 101

2 Answers2

3

I believe what you're looking to do is restore focus to the editor. If all you do is click outside the editor, the selection state doesn't change (which is why your selected text remains the same). If you then restore focus the same selection becomes visible again, without any changes to editorState.

Draft.js has some documentation about how to do this: https://draftjs.org/docs/advanced-topics-managing-focus/

The Editor component itself has a focus() method which, as you might expect, restores focus to the editor. You can gain access to the component instance with a ref:

const editorRef = React.useRef<Editor>(null)

const selectAgain = () => {
  editorRef.current.focus()
};

Then connect the ref to the component and add the click handler to the button:

<div>
  <Editor
    editorState={editorState}
    onChange={onEditorStateChange}
    placeholder={placeholder}
    ref={editorRef} // added ref
  />

  <h2>Selected text:</h2>
  <p>{getCurrentTextSelection(editorState)}</p>

  // added click handler
  <button onClick={selectAgain}>Select text again</button> 
</div>

Complete example: https://codesandbox.io/s/flamboyant-hill-l31bn

mzulch
  • 1,460
  • 12
  • 14
  • Thanks for your answer sir. Sadly I messed up my example and thats why the answer was so obvious. My real issue is when I select a text, change the `editorState`, and then try to reselect the previous selection. I upvoted your answer for your time but I will need to update my question. Sorry for that. – johannchopin Aug 24 '20 at 09:24
  • Finally my initial issue was not related to the `.focus()` itself. So your answer was really helpful. – johannchopin Aug 26 '20 at 07:27
0

Maybe you can store the selectedText into EditorState Using

EditorState.push( editorState, contentState, changeType)

More Info

Dilan
  • 2,610
  • 7
  • 23
  • 33
Mai
  • 3
  • 2