|
1 | | -import React, { useRef, forwardRef, useImperativeHandle } from 'react'; |
| 1 | +import React, { useRef, forwardRef, useImperativeHandle, useCallback } from 'react'; |
2 | 2 | import type { EditorState, EditorStateConfig, Extension, StateField } from '@codemirror/state'; |
3 | 3 | import type { EditorView, ViewUpdate } from '@codemirror/view'; |
4 | 4 | import { type BasicSetupOptions } from '@uiw/codemirror-extensions-basic-setup'; |
@@ -116,9 +116,8 @@ const ReactCodeMirror = forwardRef<ReactCodeMirrorRef, ReactCodeMirrorProps>((pr |
116 | 116 | initialState, |
117 | 117 | ...other |
118 | 118 | } = props; |
119 | | - const editor = useRef<HTMLDivElement>(null); |
120 | | - const { state, view, container } = useCodeMirror({ |
121 | | - container: editor.current, |
| 119 | + const editor = useRef<HTMLDivElement | null>(null); |
| 120 | + const { state, view, container, setContainer } = useCodeMirror({ |
122 | 121 | root, |
123 | 122 | value, |
124 | 123 | autoFocus, |
@@ -150,13 +149,23 @@ const ReactCodeMirror = forwardRef<ReactCodeMirrorRef, ReactCodeMirrorProps>((pr |
150 | 149 | view, |
151 | 150 | ]); |
152 | 151 |
|
| 152 | + const setEditorRef = useCallback( |
| 153 | + (el: HTMLDivElement) => { |
| 154 | + editor.current = el; |
| 155 | + setContainer(el); |
| 156 | + }, |
| 157 | + [setContainer], |
| 158 | + ); |
| 159 | + |
153 | 160 | // check type of value |
154 | 161 | if (typeof value !== 'string') { |
155 | 162 | throw new Error(`value must be typeof string but got ${typeof value}`); |
156 | 163 | } |
157 | 164 |
|
158 | 165 | const defaultClassNames = typeof theme === 'string' ? `cm-theme-${theme}` : 'cm-theme'; |
159 | | - return <div ref={editor} className={`${defaultClassNames}${className ? ` ${className}` : ''}`} {...other}></div>; |
| 166 | + return ( |
| 167 | + <div ref={setEditorRef} className={`${defaultClassNames}${className ? ` ${className}` : ''}`} {...other}></div> |
| 168 | + ); |
160 | 169 | }); |
161 | 170 |
|
162 | 171 | ReactCodeMirror.displayName = 'CodeMirror'; |
|
0 commit comments