Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Closed
lofti198 opened this issue Aug 28, 2022 · 8 comments
Closed

Comments

@lofti198
Copy link

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
Copy link
Member

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

@lofti198
Copy link
Author

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
Copy link
Member

This way I can't help you. @lofti198

@lofti198
Copy link
Author

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
Copy link
Member

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
Copy link
Author

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
Copy link
Author

lofti198 commented Sep 1, 2022

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants