react-codemirror2 icon indicating copy to clipboard operation
react-codemirror2 copied to clipboard

[Feature Request] Set focus via external event

Open prenx4x opened this issue 4 years ago • 3 comments

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.

prenx4x avatar Jul 14 '21 03:07 prenx4x

@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.

rafalmyszynski avatar Nov 12 '22 08:11 rafalmyszynski

@rnowak8 From where does codemirror.Editor came?

pprathameshmore avatar Nov 14 '22 06:11 pprathameshmore

@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';

rafalmyszynski avatar Nov 14 '22 07:11 rafalmyszynski