uiwjs / react-markdown-editor

A markdown editor with preview, implemented with React.js and TypeScript.
https://uiwjs.github.io/react-markdown-editor
MIT License
327 stars 32 forks source link

How to make editor focused (active with cursor in it) on component load #189

Closed lofti198 closed 2 years ago

lofti198 commented 2 years ago

How to make editor focused (active with cursor in it) on component load? I guess I should do that with useEffect, however nor using refs, neigher getting element from document did not work for me: image

jaywcjlove commented 2 years ago

@lofti198 Please provide me with an example via codesandbox.io.

lofti198 commented 2 years ago

Hi! Ready https://codesandbox.io/s/compassionate-hypatia-kgf4xc?file=/src/components/JSMindMM.js , however getting strange error: image

It worked OK on my local machine

jaywcjlove commented 2 years ago

This way I can't help you. @lofti198

lofti198 commented 2 years ago

Today I fixed issue with codesandbox and now you can see the working component here: https://codesandbox.io/p/github/lofti198/react-jsmind/draft/nostalgic-wright?file=%2Fsrc%2Fcomponents%2FJSMindMM.js . Any ideas now how to make editor get focus automatically on component mount?

jaywcjlove commented 2 years ago

@lofti198 Here is an incomplete example. https://codesandbox.io/embed/react-markdown-editor-uiwjs-react-markdown-editor-issues-189-4imdj6?fontsize=14&hidenavigation=1&theme=dark

jaywcjlove commented 2 years ago
import MarkdownEditor from "@uiw/react-markdown-editor";
import { useState, useRef, useEffect } from "react";
const code = `# title\n\nHello World!\n\n`;

export function Editor() {
  const $ref = useRef(null);
  const [markdownVal, setMarkdownVal] = useState(code);

  useEffect(() => {
    setTimeout(() => {
      const view = $ref.current?.editor.current?.view;
      if (view) {
        view.focus();
        view.dispatch(view.state.update({ selection: { anchor: 12 } }));
      }
    }, 200);
  }, [$ref]);
  return (
    <MarkdownEditor
      ref={$ref}
      value={markdownVal}
      onChange={(value, vu) => {
        setMarkdownVal(value);
      }}
      onStatistics={(data) => {
        // main = data.selectionAsSingle;
        // console.log("data:", data.selectionAsSingle);
      }}
    />
  );
}
lofti198 commented 2 years ago

Hi! Thank you very much for this work! I checked your solution in your codesandbox and it works completely cool! At the same time, when integrated in my code I somewhy get editor as null and the subsequent condition (if(view)...) doesn't do its job to set focus: https://codesandbox.io/p/github/lofti198/react-jsmind/draft/nostalgic-wright?file=%2Fsrc%2Fcomponents%2FJSMindMM.js

image

Maybe you see what I missed?

lofti198 commented 2 years ago

Finally we found that it works, but for version 5.3.0.