scniro / react-codemirror2

Codemirror integrated components for React
MIT License
1.65k stars 192 forks source link

[Feature Request] Set focus via external event #252

Open prenx4x opened 3 years ago

prenx4x commented 3 years ago

Hello,

I want to set focus to my codemirror editor via external button click. I am already using the prop options={{ autofocus: true }} and that works well when page loads. But I want a way to set focus again via a button click. How do I do that?

Thanks.

rnowak8 commented 1 year ago

@prenx4x It's possible via ref to CodeMirror editor which you can get via editorDidMount callback.

Define ref:

const cmEditorRef = useRef<codemirror.Editor>();

Save ref:

const onEditorDidMount = useCallback((editor: codemirror.Editor) => {
    cmEditorRef.current = editor;
  }, []);

Use ref:

const focusEditor = useCallback(() => {
    if (cmEditorRef.current) {
      cmEditorRef.current.focus();
    }
  }, []);

And CodeMirror usage:

<CodeMirror
    ...
    editorDidMount={onEditorDidMount}
  />

FYI TypeScript is used above.

pprathameshmore commented 1 year ago

@rnowak8 From where does codemirror.Editor came?

rnowak8 commented 1 year ago

@pprathameshmore From

import * from 'codemirror';

Type package must be installed

@types/codemirror

You can also (better) import only Editor type and use instead of codemirror.Editor.

import { Editor } from 'codemirror';