The codemirror editor support a mode that auto fit height with it's content:
http://codemirror.net/demo/resize.html
Can we make monaco-edtior auto fit content too?
The codemirror editor support a mode that auto fit height with it's content:
http://codemirror.net/demo/resize.html
Can we make monaco-edtior auto fit content too?
TL;DR: add automaticLayout: true
to your editor configuration:
monaco.editor.create( domEl, {...options, automaticLayout: true});
Your question is the general question of a previous SO question.
In my case, I'm using Monaco to provide a nicely rendered view of static code snippets in what is essentially documentation. So, I don't need for my Monaco editor instances to adapt and resize to changing content, and I'm not particularly concerned about them being responsive to changing browser windows. I just need them to render their snippets completely, no more no less, on first load and without scroll bars; little snippets in little editor windows and larger snippets in larger ones.
For whatever reason, all my attempts to use automaticLayout: true
for this purpose never worked. I also didn't have any luck with the various suggestions to call editor.layout()
. I only ever got editors that were around 10px tall. I worked around this by creating a wrapper component for monaco-editor/react that set the height of the editor based on the scroll bar height after the editor is mounted.
import * as React from "react";
import Editor from "@monaco-editor/react";
import { Monaco } from "@monaco-editor/react";
import { editor } from "monaco-editor";
export interface IMonacoWrapperProps {
content: string;
options?: editor.IStandaloneEditorConstructionOptions;
className?: string;
}
export function MonacoWrapper(props: IMonacoWrapperProps): JSX.Element {
const [editorHeight, setEditorHeight] = React.useState(0);
function editorDidMount(
editor: editor.IStandaloneCodeEditor,
monaco: Monaco
) {
const scrollHeight = editor.getScrollHeight();
setEditorHeight(scrollHeight);
}
return (
<div>
<Editor
height={editorHeight}
defaultLanguage="typescript"
defaultValue={props.content}
options={props.options}
onMount={editorDidMount}
className={props.className}
/>
</div>
);
}
Here's a link to a demo of this in CodeSandbox: https://codesandbox.io/s/autosize-monaco-editor-to-content-on-first-load-dwvxlv?file=/src/MonacoWrapper.tsx