Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In SlateJS, how to change focus to specific editor when multiple editors are present?

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
like image 239
haz Avatar asked Apr 15 '20 07:04

haz


Video Answer


1 Answers

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+)

like image 117
Sherwin Yu Avatar answered Oct 13 '22 09:10

Sherwin Yu