Search code examples
reactjstinymce

@tinymce/tinymce-react - How do I change in code the focus?


I try to focus the TinyMCE text editor by pressing a button, with auto_focus it does not work, unfortunately. My TinyMCE component use:

<Editor
        apiKey='*************'
        onInit={(evt, editor) => editorRef.current = editor}
        init={{
          height: 500,
          width: "100%",
          auto_focus: isInFocus, // not working
          menubar: false,
          inline: true,
          plugins: [

          ],
          toolbar: 'bold italic underline | undo redo | alignleft aligncenter ' +
          'alignright alignjustify',
          content_style: 'body { font-family:Helvetica,Arial,sans-serif; font-size:14px }'
        }}
      />

The solutions on the internet do not talk about the package npm @tinymce/tinymce-react. Thanks for the helpers.


Solution

  • I found the solution myself pretty quickly: I used the useEffect hook and the editorRef.current.focus() function:

    export default function TinymceInlineEditor({isInFocus}) {
      const editorRef = useRef(null);
    
      useEffect(() => {
          isInFocus ? editorRef.current.focus() : null;
        }, [isInFocus]);
    
      return (
          <Editor
            apiKey='************'
            onInit={(evt, editor) => editorRef.current = editor}
            onBlur={(e) => handelBlur(editorRef)}
            init={{
              height: 500,
              width: "100%",
              menubar: false,
              inline: true,
              plugins: [
    
              ],
              toolbar: 'bold italic underline | undo redo | alignleft aligncenter ' +
              'alignright alignjustify',
              content_style: 'body { font-family:Helvetica,Arial,sans-serif; font-size:14px }'
            }}
          />
      );
    }