cramos24
cramos24

Reputation: 39

My monaco editor instance fails to update

The issue:

I'm attempting to integrate monaco-editor/react into my web application and have successfully loaded it, but encounter an error whenever I change it in my front-end.

Everything works as expected until I modify my editor instance in any way (i.e. add text, resize, etc.)

The web application I'm using, Grafana, spits out this error whenever I interact with my editor

My error:

error message

My code:

import Editor from '@monaco-editor/react';
...

interface MonacoEditorProps {
  value: string;
  theme: string;
  language: string;
  onChange: (value?: string | undefined) => void;
}
class MonacoEditor extends React.PureComponent<MonacoEditorProps> {
  getEditorValue: any | undefined;
  editorInstance: any | undefined;

  onSourceChange = () => {
    this.props.onChange(this.getEditorValue());
  };
  onEditorDidMount = (getEditorValue: any, editorInstance: any) => {
    this.getEditorValue = getEditorValue;
    this.editorInstance = editorInstance;
  };
  updateDimensions() {
    this.editorInstance.layout();
  }
  render() {
    const source = this.props.value;
    if (this.editorInstance) {
      this.editorInstance.layout();
    }
    return (
      <div onBlur={this.onSourceChange}>
        <Editor
          height={'33vh'}
          language={this.props.language}
          theme={this.props.theme}
          value={source}
          onMount={this.onEditorDidMount}
        />
      </div>
    );
  }
}

Don't think I'm deviating from the editor instance docs too much. Does anyone know how I'm updating my editor incorrectly?

Upvotes: 0

Views: 1893

Answers (1)

Mike Lischke
Mike Lischke

Reputation: 53307

I don't know why onMount is still available, but I have used the normal componentDidMount method of the React component for layout and used a ref for the actual editor instance. This works excellently:

    private editorRef = React.createRef<Editor>();

...

                <Editor
                    ref={this.editorRef}
                    language={language}
                    options={opts}
                />

and

    public componentDidMount(): void {
        this.editorRef.current?.editor?.layout();
        if (autofocus) {
            this.editorRef.current?.editor?.focus();
        }
    }

Upvotes: 1

Related Questions