react-codemirror
CodeMirror component for React. Demo Preview: @uiwjs.github.io/react-codemirror
Features:
🚀 Quickly and easily configure the API.
🌱 Versions after @uiw/react-codemirror@v4
use codemirror 6. #88.
⚛️ Support the features of React Hook(requires React 16.8+).
📚 Use Typescript to write, better code hints.
🌐 The bundled version supports use directly in the browser #267.
🌎 There are better sample previews.
🎨 Support theme customization, provide theme editor.
Install
Not dependent on uiw.
npm install @uiw/react-codemirror --save
All Packages
Name | NPM Version | Website |
---|
@uiw/react-codemirror | | #preview |
@uiw/codemirror-extensions-basic-setup | | #preview |
@uiw/codemirror-extensions-color | | #preview |
@uiw/codemirror-extensions-classname | | #preview |
@uiw/codemirror-extensions-events | | #preview |
@uiw/codemirror-extensions-hyper-link | | #preview |
@uiw/codemirror-extensions-langs | | #preview |
@uiw/codemirror-extensions-line-numbers-relative | | #preview |
@uiw/codemirror-extensions-mentions | | #preview |
@uiw/codemirror-extensions-zebra-stripes | | #preview |
@uiw/codemirror-themes | | #preview |
Usage
import React from 'react';
import CodeMirror from '@uiw/react-codemirror';
import { javascript } from '@codemirror/lang-javascript';
function App() {
const onChange = React.useCallback((value, viewUpdate) => {
console.log('value:', value);
}, []);
return (
<CodeMirror
value="console.log('hello world!');"
height="200px"
extensions={[javascript({ jsx: true })]}
onChange={onChange}
/>
);
}
export default App;
Support Language
import CodeMirror from '@uiw/react-codemirror';
import { StreamLanguage } from '@codemirror/language';
import { go } from '@codemirror/legacy-modes/mode/go';
const goLang = `package main
import "fmt"
func main() {
fmt.Println("Hello, 世界")
}`;
export default function App() {
return <CodeMirror value={goLang} height="200px" extensions={[StreamLanguage.define(go)]} />;
}
Markdown Example
Markdown language code is automatically highlighted.
import CodeMirror from '@uiw/react-codemirror';
import { markdown, markdownLanguage } from '@codemirror/lang-markdown';
import { languages } from '@codemirror/language-data';
const code = `## Title
\`\`\`jsx
function Demo() {
return <div>demo</div>
}
\`\`\`
\`\`\`bash
# Not dependent on uiw.
npm install @codemirror/lang-markdown --save
npm install @codemirror/language-data --save
\`\`\`
[weisit ulr](https://uiwjs.github.io/react-codemirror/)
\`\`\`go
package main
import "fmt"
func main() {
fmt.Println("Hello, 世界")
}
\`\`\`
`;
export default function App() {
return <CodeMirror value={code} extensions={[markdown({ base: markdownLanguage, codeLanguages: languages })]} />;
}
Codemirror Merge
import CodeMirrorMerge from 'react-codemirror-merge';
import { EditorView } from 'codemirror';
import { EditorState } from '@codemirror/state';
const Original = CodeMirrorMerge.Original;
const Modified = CodeMirrorMerge.Modified;
let doc = `one
two
three
four
five`;
export const Example = () => {
return (
<CodeMirrorMerge>
<Original value={doc} />
<Modified
value={doc.replace(/t/g, 'T') + 'Six'}
extensions={[EditorView.editable.of(false), EditorState.readOnly.of(true)]}
/>
</CodeMirrorMerge>
);
};
Support Hook
import { useEffect, useMemo, useRef } from 'react';
import { useCodeMirror } from '@uiw/react-codemirror';
import { javascript } from '@codemirror/lang-javascript';
const code = "console.log('hello world!');\n\n\n";
const extensions = [javascript()];
export default function App() {
const editor = useRef();
const { setContainer } = useCodeMirror({
container: editor.current,
extensions,
value: code,
});
useEffect(() => {
if (editor.current) {
setContainer(editor.current);
}
}, [editor.current]);
return <div ref={editor} />;
}
Using Theme
We have created a theme editor
where you can define your own theme. We have also defined some themes ourselves, which can be installed and used directly. Below is a usage example:
import CodeMirror from '@uiw/react-codemirror';
import { javascript } from '@codemirror/lang-javascript';
import { okaidia } from '@uiw/codemirror-theme-okaidia';
const extensions = [javascript({ jsx: true })];
export default function App() {
return (
<CodeMirror
value="console.log('hello world!');"
height="200px"
theme={okaidia}
extensions={[javascript({ jsx: true })]}
/>
);
}
Using custom theme
import CodeMirror from '@uiw/react-codemirror';
import { createTheme } from '@uiw/codemirror-themes';
import { javascript } from '@codemirror/lang-javascript';
import { tags as t } from '@lezer/highlight';
const myTheme = createTheme({
theme: 'light',
settings: {
background: '#ffffff',
foreground: '#75baff',
caret: '#5d00ff',
selection: '#036dd626',
selectionMatch: '#036dd626',
lineHighlight: '#8a91991a',
gutterBackground: '#fff',
gutterForeground: '#8a919966',
},
styles: [
{ tag: t.comment, color: '#787b8099' },
{ tag: t.variableName, color: '#0080ff' },
{ tag: [t.string, t.special(t.brace)], color: '#5c6166' },
{ tag: t.number, color: '#5c6166' },
{ tag: t.bool, color: '#5c6166' },
{ tag: t.null, color: '#5c6166' },
{ tag: t.keyword, color: '#5c6166' },
{ tag: t.operator, color: '#5c6166' },
{ tag: t.className, color: '#5c6166' },
{ tag: t.definition(t.typeName), color: '#5c6166' },
{ tag: t.typeName, color: '#5c6166' },
{ tag: t.angleBracket, color: '#5c6166' },
{ tag: t.tagName, color: '#5c6166' },
{ tag: t.attributeName, color: '#5c6166' },
],
});
const extensions = [javascript({ jsx: true })];
export default function App() {
const onChange = React.useCallback((value, viewUpdate) => {
console.log('value:', value);
}, []);
return (
<CodeMirror
value="console.log('hello world!');"
height="200px"
theme={myTheme}
extensions={extensions}
onChange={onChange}
/>
);
}
Use initialState
to restore state from JSON-serialized representation
CodeMirror allows to serialize editor state to JSON representation with toJSON function for persistency or other needs. This JSON representation can be later used to recreate ReactCodeMirror component with the same internal state.
For example, this is how undo history can be saved in the local storage, so that it remains after the page reloads
import CodeMirror from '@uiw/react-codemirror';
import { historyField } from '@codemirror/commands';
const stateFields = { history: historyField };
export function EditorWithInitialState() {
const serializedState = localStorage.getItem('myEditorState');
const value = localStorage.getItem('myValue') || '';
return (
<CodeMirror
value={value}
initialState={
serializedState
? {
json: JSON.parse(serializedState || ''),
fields: stateFields,
}
: undefined
}
onChange={(value, viewUpdate) => {
localStorage.setItem('myValue', value);
const state = viewUpdate.state.toJSON(stateFields);
localStorage.setItem('myEditorState', JSON.stringify(state));
}}
/>
);
}
Props
value?: string
value of the auto created model in the editor.width?: string
width of editor. Defaults to auto
.height?: string
height of editor. Defaults to auto
.theme?
: 'light'
/ 'dark'
/ Extension
Defaults to 'light'
.
import React from 'react';
import { EditorState, EditorStateConfig, Extension } from '@codemirror/state';
import { EditorView, ViewUpdate } from '@codemirror/view';
export * from '@codemirror/view';
export * from '@codemirror/basic-setup';
export * from '@codemirror/state';
export interface UseCodeMirror extends ReactCodeMirrorProps {
container?: HTMLDivElement | null;
}
export declare function useCodeMirror(props: UseCodeMirror): {
state: EditorState | undefined;
setState: import('react').Dispatch<import('react').SetStateAction<EditorState | undefined>>;
view: EditorView | undefined;
setView: import('react').Dispatch<import('react').SetStateAction<EditorView | undefined>>;
container: HTMLDivElement | null | undefined;
setContainer: import('react').Dispatch<import('react').SetStateAction<HTMLDivElement | null | undefined>>;
};
export interface ReactCodeMirrorProps
extends Omit<EditorStateConfig, 'doc' | 'extensions'>,
Omit<React.HTMLAttributes<HTMLDivElement>, 'onChange' | 'placeholder'> {
value?: string;
height?: string;
minHeight?: string;
maxHeight?: string;
width?: string;
minWidth?: string;
maxWidth?: string;
autoFocus?: boolean;
placeholder?: string | HTMLElement;
theme?: 'light' | 'dark' | Extension;
basicSetup?: boolean | BasicSetupOptions;
editable?: boolean;
readOnly?: boolean;
indentWithTab?: boolean;
onChange?(value: string, viewUpdate: ViewUpdate): void;
onStatistics?(data: Statistics): void;
onCreateEditor?(view: EditorView, state: EditorState): void;
onUpdate?(viewUpdate: ViewUpdate): void;
extensions?: Extension[];
root?: ShadowRoot | Document;
initialState?: {
json: any;
fields?: Record<'string', StateField<any>>;
};
}
export interface ReactCodeMirrorRef {
editor?: HTMLDivElement | null;
state?: EditorState;
view?: EditorView;
}
declare const ReactCodeMirror: React.ForwardRefExoticComponent<
ReactCodeMirrorProps & React.RefAttributes<ReactCodeMirrorRef>
>;
export default ReactCodeMirror;
export interface BasicSetupOptions {
lineNumbers?: boolean;
highlightActiveLineGutter?: boolean;
highlightSpecialChars?: boolean;
history?: boolean;
foldGutter?: boolean;
drawSelection?: boolean;
dropCursor?: boolean;
allowMultipleSelections?: boolean;
indentOnInput?: boolean;
syntaxHighlighting?: boolean;
bracketMatching?: boolean;
closeBrackets?: boolean;
autocompletion?: boolean;
rectangularSelection?: boolean;
crosshairCursor?: boolean;
highlightActiveLine?: boolean;
highlightSelectionMatches?: boolean;
closeBracketsKeymap?: boolean;
defaultKeymap?: boolean;
searchKeymap?: boolean;
historyKeymap?: boolean;
foldKeymap?: boolean;
completionKeymap?: boolean;
lintKeymap?: boolean;
}
import { EditorSelection, SelectionRange } from '@codemirror/state';
import { ViewUpdate } from '@codemirror/view';
export interface Statistics {
lineCount: number;
length: number;
lineBreak: string;
readOnly: boolean;
tabSize: number;
selection: EditorSelection;
selectionAsSingle: SelectionRange;
ranges: readonly SelectionRange[];
selectionCode: string;
selections: string[];
selectedText: boolean;
}
export declare const getStatistics: (view: ViewUpdate) => Statistics;
Related
Contributors
As always, thanks to our amazing contributors!
Made with github-action-contributors.
License
Licensed under the MIT License.