I have multiple SlateJS editors in my app, representing individual pages. When I add a new page, I want the focus to be changed to the editor within that page.
I have no idea how to do this! I've checked in the docs and there are onFocus
and onBlur
hook plugins, but this is for reacting to focus changes. On the slack community snippets there is this:
// Moving cursor to the end of the document
ReactEditor.focus(editor);
Transforms.select(editor, Editor.end(editor, []));
But I can't get this to work either. This is a cut-down version of my code:
Root element
<div>
{pages.map((pageID: number) => (
<Page onChange={updatePage(pageID)}/>
))}
</div>
Page Element
<div>
<Input onChange={onChange}/>
</div>
And then the <Input/>
element renders the Slate
and Editable
components from slate-react
.
I've tried to RTFM but I legitiamtely cannot find anything about managing focus aside from that plugins page.
I've tried adding a focusOnRender
boolean prop, and using it a hook on the Input
element:
useEffect(() => {
if (focusOnRender)
ReactEditor.focus(editor);
}, [focusOnRender]);
But this just doesn't work for me.
I've found this page in the docs which describes an editor.focus()
function, but when I try this I get the following error:
TypeError: editor.focus is not a function
Not sure if this helps, but I've had some success with wrapping ReactEditor.focus(editor)
inside a setTimeout(). I do this outside of the component tree (e.g., instead of puttting it in useEffect
of a component, try putting it in an event handler, or calling it from console).
FYI, the editor.focus()
docs you're referencing are on Slate 0.47, and the API has changed significantly in 0.50+ (if you're using the Transforms.select
or ReactEditor.focus
API, you're on version 0.50+)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With