uiwjs / react-codemirror

CodeMirror 6 component for React. @codemirror https://uiwjs.github.io/react-codemirror/
https://uiwjs.github.io/react-codemirror/
MIT License
1.55k stars 126 forks source link

setting scroll dynamically #435

Open StarkovSergey opened 1 year ago

StarkovSergey commented 1 year ago

How to dynamically set scroll for CodeMirror component? I use ref + querySelector('.cm-scroller'), but is there a better way?

jaywcjlove commented 1 year ago

@StarkovSergey https://github.com/uiwjs/react-codemirror/blob/86c484572bbbec32d64735f975ce0e2a8b51c6cb/extensions/events/src/index.ts#L20-L48

It may be an extensions @StarkovSergey

StarkovSergey commented 1 year ago

@jaywcjlove I understand how I can get scrollTop value with this extension, but how to set scrollTop isn't obvious for me

sahilatahar commented 6 months ago

I also have the same problem. I got the scrollTop Value but how to scroll editor

patrikbraborec commented 2 months ago

Have anyone figured it out? I have the same issue. Thanks!

patrikbraborec commented 2 months ago

I found solution that works for me.

  1. Get ref of CodeMirror:
const editorRef = useRef<ReactCodeMirrorRef>();

const editorCallback = (editor: ReactCodeMirrorRef) => {
    if (!editorRef.current && editor?.editor && editor?.state && editor?.view) {
      editorRef.current = editor;
    }
};

...
<CodeMirror
    ...
    ref={editorCallback}
    ...
/>
...
  1. Then, I do something like this:

I do it in useEffect but it might not be the best solution for your use case (more info: https://legacy.reactjs.org/docs/hooks-faq.html?source=post_page-----eb7c15198780--------------------------------#how-can-i-measure-a-dom-node).

...

if (editorRef.current) {
      const current = editorRef.current;
      const totalHeight = current.editor?.scrollHeight || 0;
      current.editor?.scrollTo(0, totalHeight);
}

...

Also applies for: https://github.com/uiwjs/react-codemirror/issues/617.