Last active
December 19, 2021 15:09
-
-
Save sachinraja/08e6ef7d4b1ba67015fff6b8844a3ad0 to your computer and use it in GitHub Desktop.
Basic React implementation of https://github.com/codemirror/codemirror.next. View working example: https://stackblitz.com/edit/vitejs-vite-8s3guc?file=src%2FEditor.tsx&terminal=dev
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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} />; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks! Fixed that and cleaned up some parts. If you want a more complete implementation you can use https://github.com/sachinraja/rodemirror.