I'm working on a React project that has a pair of Lexical rich text editors on the page. I'm trying to achieve the following: My cursor is somewhere within one of the editors, then I click a button or link somewhere outside/independent of the editor on the page, and a text string is inserted in the editor where my cursor was.
The problem is that by clicking on the button outside the editor, the editor no longer has focus, so I get the "editor is not defined" error when trying to call editor.update()
.
Apologies for not being able to post more of the code per security rules, but has anyone ever tried/done something similar in concept?
Here is a paired down version of the code (can't post the actual code per work rules). Note the sections commented as "Attempt :" were never all there in combination - just showing some variations I've tried unsuccessfully.
function createEditorInstance(myEditorID, initialValue) {
const theEditorRef = useRef();
doInsertText = (someText, someEditorID) => {
/*-- Attempt 1 (this line doesn't error, but focus remains on button; "editor" remains undefined): --*/
theEditorRef.current.focus();
/*-- Attempt 2 (this line doesn't error, but focus remains on button; "editor" remains undefined): --*/
theEditorRef.current.click();
/*-- Attempt 3 (this line doesn't error, and focus seems to go to editor (typing inserts chars where cursor was), but "editor" still stays undefined): --*/
document.getElementById(someEditorID).focus();
/*-- Attempt 4 (this line doesn't error, but focus remains on button; "editor" remains undefined): --*/
document.getElementById(someEditorID).click();
/*-- Attempt 5 (this is just a concept, is essentially what I'm asking for): --*/
setLexicalEditorFocus(someEditorID);
/*-- Can't do this in combo with any of above or by itself, because it results in an "invalid hook" since this isn't a function component. --*/
// editor = useLexicalComposerContext();
/*-- Update the editor (results in "editor is undefined" error, because the editor doesn't have focus after clicking the buttton outside the editor): --*/
editor.update(() => {
const textNode = $createTextNode(someText);
const selection = $getSelection();
if (selection) {
selection.insertNodes([textNode]);
}
}
}
return (
<>
<LexicalEditor
id={myEditorID}
initialValue={initialValue}
toolbar={{ toolList: myToolList }}
theEditorRef={theEditorRef}
/>
<button onClick={() => {doInsertText('Some text string', myEditorID)}}>Insert Some Text</button>
</>
);
}
I also looked at forwardRef, but my understanding from docs is that it's deprecated in favor of custom refs (hence the attempted "theEditorRef").