Skip to content

Instantly share code, notes, and snippets.

@sachinraja
Last active December 19, 2021 15:09
Show Gist options
  • Save sachinraja/08e6ef7d4b1ba67015fff6b8844a3ad0 to your computer and use it in GitHub Desktop.
Save sachinraja/08e6ef7d4b1ba67015fff6b8844a3ad0 to your computer and use it in GitHub Desktop.
// view at: https://stackblitz.com/edit/vitejs-vite-8s3guc?file=src%2FEditor.tsx&terminal=dev
import React, { useRef, useEffect } from 'react';
import { EditorView, ViewUpdate } from '@codemirror/view';
import { EditorState, Extension } from '@codemirror/state';
import { basicSetup } from '@codemirror/basic-setup';
import { javascript } from '@codemirror/lang-javascript';
import { oneDark } from '@codemirror/theme-one-dark';
interface EditorProps {
value?: string;
onUpdate?: (update: ViewUpdate) => void;
}
export const Editor = ({ value = '', onUpdate }: EditorProps) => {
const editor = useRef<HTMLDivElement>(null);
useEffect(() => {
const extensions: Extension[] = [
basicSetup,
oneDark,
javascript({ typescript: true }),
];
if (onUpdate) extensions.push(EditorView.updateListener.of(onUpdate));
const state = EditorState.create({
doc: value,
extensions,
});
const view = new EditorView({ state, parent: editor.current! });
return () => view.destroy();
}, [editor]);
return <div ref={editor} />;
};
@jpomykala
Copy link

jpomykala commented Nov 30, 2021

TSX example

import { EditorView, ViewUpdate } from "@codemirror/view";

instead

import { EditorView } from "@codemirror/view";

Thanks for sharing! Finally, I don't have to switch CodeMirror wrappers every week due to lack of maintainers. 😄

@sachinraja
Copy link
Author

Thanks! Fixed that and cleaned up some parts. If you want a more complete implementation you can use https://github.com/sachinraja/rodemirror.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment