• Stars
    star
    1,484
  • Rank 30,945 (Top 0.7 %)
  • Language
    TypeScript
  • License
    MIT License
  • Created about 6 years ago
  • Updated 21 days ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

CodeMirror 6 component for React. @codemirror https://uiwjs.github.io/react-codemirror/

react-codemirror logo

react-codemirror

jsdelivr CDN NPM Downloads Build & Deploy Open in unpkg npm version Coverage Status Open in Gitpod

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 npm version NPM Downloads #preview
react-codemirror-merge npm version NPM Downloads #preview
@uiw/codemirror-extensions-basic-setup npm version NPM Downloads #preview
@uiw/codemirror-extensions-color npm version NPM Downloads #preview
@uiw/codemirror-extensions-classname npm version NPM Downloads #preview
@uiw/codemirror-extensions-events npm version NPM Downloads #preview
@uiw/codemirror-extensions-hyper-link npm version NPM Downloads #preview
@uiw/codemirror-extensions-langs npm version NPM Downloads #preview
@uiw/codemirror-extensions-line-numbers-relative npm version NPM Downloads #preview
@uiw/codemirror-extensions-mentions npm version NPM Downloads #preview
@uiw/codemirror-extensions-zebra-stripes npm version NPM Downloads #preview
@uiw/codemirror-themes npm version NPM Downloads #preview
Name NPM Version Website
@uiw/codemirror-themes-all npm version NPM Downloads #preview
@uiw/codemirror-theme-abcdef npm version NPM Downloads #preview
@uiw/codemirror-theme-androidstudio npm version NPM Downloads #preview
@uiw/codemirror-theme-atomone npm version NPM Downloads #preview
@uiw/codemirror-theme-aura npm version NPM Downloads #preview
@uiw/codemirror-theme-bbedit npm version NPM Downloads #preview
@uiw/codemirror-theme-bespin npm version NPM Downloads #preview
@uiw/codemirror-theme-duotone npm version NPM Downloads #preview
@uiw/codemirror-theme-dracula npm version NPM Downloads #preview
@uiw/codemirror-theme-darcula npm version NPM Downloads #preview
@uiw/codemirror-theme-eclipse npm version NPM Downloads #preview
@uiw/codemirror-theme-github npm version NPM Downloads #preview
@uiw/codemirror-theme-gruvbox-dark npm version NPM Downloads #preview
@uiw/codemirror-theme-material npm version NPM Downloads #preview
@uiw/codemirror-theme-noctis-lilac npm version NPM Downloads #preview
@uiw/codemirror-theme-nord npm version NPM Downloads #preview
@uiw/codemirror-theme-okaidia npm version NPM Downloads #preview
@uiw/codemirror-theme-solarized npm version NPM Downloads #preview
@uiw/codemirror-theme-sublime npm version NPM Downloads #preview
@uiw/codemirror-theme-tokyo-night npm version NPM Downloads #preview
@uiw/codemirror-theme-tokyo-night-storm npm version NPM Downloads #preview
@uiw/codemirror-theme-tokyo-night-day npm version NPM Downloads #preview
@uiw/codemirror-theme-vscode npm version NPM Downloads #preview
@uiw/codemirror-theme-xcode npm version NPM Downloads #preview

Usage

Open in CodeSandbox

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

Open in CodeSandbox

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.

Open in CodeSandbox

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

Open in CodeSandbox

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";
// Define the extensions outside the component for the best performance.
// If you need dynamic extensions, use React.useMemo to minimize reference changes
// which cause costly re-renders.
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';

// When custom fields should be serialized, you can pass them in as an object mapping property names to fields.
// See [toJSON](https://codemirror.net/docs/ref/#state.EditorState.toJSON) documentation for more details
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 of the auto created model in the editor. */
  value?: string;
  height?: string;
  minHeight?: string;
  maxHeight?: string;
  width?: string;
  minWidth?: string;
  maxWidth?: string;
  /** focus on the editor. */
  autoFocus?: boolean;
  /** Enables a placeholder—a piece of example content to show when the editor is empty. */
  placeholder?: string | HTMLElement;
  /**
   * `light` / `dark` / `Extension` Defaults to `light`.
   * @default light
   */
  theme?: 'light' | 'dark' | Extension;
  /**
   * Whether to optional basicSetup by default
   * @default true
   */
  basicSetup?: boolean | BasicSetupOptions;
  /**
   * This disables editing of the editor content by the user.
   * @default true
   */
  editable?: boolean;
  /**
   * This disables editing of the editor content by the user.
   * @default false
   */
  readOnly?: boolean;
  /**
   * Controls whether pressing the `Tab` key inserts a tab character and indents the text (`true`)
   * or behaves according to the browser's default behavior (`false`).
   * @default true
   */
  indentWithTab?: boolean;
  /** Fired whenever a change occurs to the document. */
  onChange?(value: string, viewUpdate: ViewUpdate): void;
  /** Some data on the statistics editor. */
  onStatistics?(data: Statistics): void;
  /** The first time the editor executes the event. */
  onCreateEditor?(view: EditorView, state: EditorState): void;
  /** Fired whenever any state change occurs within the editor, including non-document changes like lint results. */
  onUpdate?(viewUpdate: ViewUpdate): void;
  /**
   * Extension values can be [provided](https://codemirror.net/6/docs/ref/#state.EditorStateConfig.extensions) when creating a state to attach various kinds of configuration and behavior information.
   * They can either be built-in extension-providing objects,
   * such as [state fields](https://codemirror.net/6/docs/ref/#state.StateField) or [facet providers](https://codemirror.net/6/docs/ref/#state.Facet.of),
   * or objects with an extension in its `extension` property. Extensions can be nested in arrays arbitrarily deep—they will be flattened when processed.
   */
  extensions?: Extension[];
  /**
   * If the view is going to be mounted in a shadow root or document other than the one held by the global variable document (the default), you should pass it here.
   * Originally from the [config of EditorView](https://codemirror.net/6/docs/ref/#view.EditorView.constructor%5Econfig.root)
   */
  root?: ShadowRoot | Document;
  /**
   * Create a state from its JSON representation serialized with [toJSON](https://codemirror.net/docs/ref/#state.EditorState.toJSON) function
   */
  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 {
  /** Get the number of lines in the editor. */
  lineCount: number;
  /** total length of the document */
  length: number;
  /** Get the proper [line-break](https://codemirror.net/docs/ref/#state.EditorState^lineSeparator) string for this state. */
  lineBreak: string;
  /** Returns true when the editor is [configured](https://codemirror.net/6/docs/ref/#state.EditorState^readOnly) to be read-only. */
  readOnly: boolean;
  /** The size (in columns) of a tab in the document, determined by the [`tabSize`](https://codemirror.net/6/docs/ref/#state.EditorState^tabSize) facet. */
  tabSize: number;
  /** Cursor Position */
  selection: EditorSelection;
  /** Make sure the selection only has one range. */
  selectionAsSingle: SelectionRange;
  /** Retrieves a list of all current selections. */
  ranges: readonly SelectionRange[];
  /** Get the currently selected code. */
  selectionCode: string;
  /**
   * The length of the given array should be the same as the number of active selections.
   * Replaces the content of the selections with the strings in the array.
   */
  selections: string[];
  /** Return true if any text is selected. */
  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.

More Repositories

1

province-city-china

🇨🇳最全最新中国【省、市、区县、乡镇街道】json,csv,sql数据
JavaScript
2,284
star
2

react-md-editor

A simple markdown editor with preview, implemented with React.js and TypeScript.
TypeScript
2,003
star
3

uiw

⚛️ @uiwjs A high quality UI Toolkit, A Component Library for React 16+.
TypeScript
702
star
4

react-login-page

Some `react` login pages, which can be used quickly after installation.
TypeScript
533
star
5

react-textarea-code-editor

A simple code editor with syntax highlighting.
TypeScript
459
star
6

react-amap

基于 React 封装的高德地图组件,帮助你轻松的接入地图到 React 项目中。
TypeScript
393
star
7

react-markdown-editor

A markdown editor with preview, implemented with React.js and TypeScript.
TypeScript
299
star
8

react-monacoeditor

Monaco Editor component for React.
TypeScript
284
star
9

react-markdown-preview

React component preview markdown text in web browser. The minimal amount of CSS to replicate the GitHub Markdown style. Support dark-mode/night mode.
TypeScript
248
star
10

react-color

🎨 Is a tiny color picker widget component for React apps.
TypeScript
238
star
11

react-baidu-map

基于 React 封装的百度地图组件,支持 React Hook,帮助你轻松的接入地图到 React 项目中。
TypeScript
216
star
12

react-native-alipay

基于 React Native 的宝支付包,已更新到最新的支付宝 SDK 版本,支持Android/iOS。
Java
199
star
13

react-heat-map

A lightweight calendar heatmap react component built on SVG, customizable version of GitHub's contribution graph.
TypeScript
178
star
14

react-json-view

A React component for displaying and editing javascript arrays and JSON objects.
TypeScript
154
star
15

icons

The premium icon font for @uiwjs Component Library. https://uiwjs.github.io/icons
HTML
138
star
16

npm-unpkg

A web application to view npm package files, Based on unpkg.
TypeScript
99
star
17

react-split

A piece of view can be divided into areas where the width or height can be adjusted by dragging.
TypeScript
60
star
18

react-code-preview

Code edit preview for React.
TypeScript
58
star
19

react-native-uiw

A UI component library based on React Native (Android & iOS).
TypeScript
44
star
20

json-viewer

Online JSON Viewer, JSON Beautifier to beautify and tree view of JSON data - It works as JSON Pretty Print to pretty print JSON data.
TypeScript
42
star
21

react-native-amap-geolocation

React Native 高德地图定位模块,支持 Android/iOS。
Java
41
star
22

react-signature

A signature board component for react.
TypeScript
34
star
23

react-watermark

A react component that adds a watermark to an area of a web page.
TypeScript
31
star
24

react-native-wechat

React Native 包使用微信分享、登录、收藏、支付等功能,支持Android/iOS。
Java
30
star
25

file-icons

File icons in the file tree.
HTML
29
star
26

uiw-admin

UIW-Admin Panel Framework, Powered by React and @uiwjs.
TypeScript
22
star
27

babel-plugin-transform-remove-imports

Remove the specified import declaration when you use the babel transform to build the package.
JavaScript
21
star
28

react-run-web

Online Code Editor for Rapid Web Development.
TypeScript
20
star
29

react-native-template

React Native template for react-native-uiw.
JavaScript
17
star
30

react-mac-keyboard

Macbook computer keyboard style for react component.
TypeScript
17
star
31

next-remove-imports

The default behavior is to remove all .less/.css/.scss/.sass/.styl imports from all packages in node_modules.
JavaScript
17
star
32

ui-color

Converting HEX & RGB colors to UIColor/NSColor/Color for both Objective C & Swift.
TypeScript
16
star
33

copy-to-clipboard

Copy text to the clipboard in modern browsers
JavaScript
16
star
34

react-use-online

useOnline is a tiny, zero-dependency hook for responding to online/offline changes.
TypeScript
16
star
35

reset-css

A tiny modern CSS reset.
CSS
14
star
36

keycode-info

A simple web page that responds to the pressed key and returns information about the JavaScript'on-key press' key.
TypeScript
14
star
37

react-iframe

This component allows you to wrap your entire React application or each component in an <iframe>.
TypeScript
12
star
38

react-codesandbox

A React component is provided that allows you to programmatically generate codesandbox projects from code samples on the fly.
TypeScript
11
star
39

react-github-corners

Add a Github corner to your project page, This GitHub corner for react component/web component.
TypeScript
11
star
40

react-only-when

A declarative component for conditional rendering.
TypeScript
9
star
41

bootstrap-icons

Official open source SVG icon library for Bootstrap.
8
star
42

uiwjs.github.io

The official documentation site for @uiwjs. https://uiwjs.github.io
8
star
43

react-clock

An analog clock for your React app.
TypeScript
7
star
44

vscode-uiw

Preview uiw document in vscode.
TypeScript
7
star
45

react-layout

Layout component for React. Handling the overall layout of a page.
TypeScript
7
star
46

react-csv-reader

React component that handles csv file input and its parsing.
TypeScript
7
star
47

react-use-colorscheme

useColorScheme() provides access to the devices color scheme.
TypeScript
7
star
48

react-native-transport-location

Objective-C
6
star
49

react-code-preview-layout

A react component showing the layout of `code` and `code preview example`.
TypeScript
6
star
50

date-formatter

Get a formatted date.
TypeScript
6
star
51

react-prismjs

React Component for prismjs.
TypeScript
6
star
52

react-tabs-draggable

Draggable tabs for React.
TypeScript
5
star
53

react-markdown-preview-example

Preview the markdown files and run the React examples in the documentation.
TypeScript
5
star
54

react-head

React components will manage your changes to the document head
TypeScript
4
star
55

react-shields

Shields.io for react component, Quality metadata badges for open source projects.
TypeScript
4
star
56

react-codepen

A React component is provided that allows you to programmatically generate codepen projects from code samples on the fly.
TypeScript
4
star
57

react-stackblitz

A React component is provided that allows you to programmatically generate stackblitz projects from code samples on the fly.
TypeScript
4
star
58

react-back-to-top

A minimal lightweight react component for adding a nice scroll up (back to top) button with onScroll progress.
TypeScript
4
star
59

react-monorepo-template

Simple React package development project example template.
TypeScript
3
star
60

auto-gitee-mirror

Use GitHub Actions to sync from GitHub to Gitee
3
star
61

react-keywords

Highlight a keyword in a piece of text and return a React element.
TypeScript
3
star
62

css-filter

A filter CSS generator that helps you quickly generate filter CSS declarations for your website. It comes with many options and it demonstrates instantly.
TypeScript
3
star
63

babel-plugin-transform-uiw-import

Modular import plugin for babel.
JavaScript
2
star
64

react-xml-reader

React component that handles xml file input and its parsing.
TypeScript
2
star
65

rematch-loading

Loading indicator plugin for @rematch.
TypeScript
1
star
66

logo

Source files of uiw's logo.
1
star
67

.github

Welcome to the uiwjs organization.
1
star