CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-uiw--react-codemirror

React wrapper component for CodeMirror 6 editor with TypeScript support and extensible theming system

Pending
Overview
Eval results
Files

main-component.mddocs/

Main Component

The primary React component that renders a CodeMirror 6 editor with full configuration support and declarative React interface.

Capabilities

ReactCodeMirror Component

The main component providing a complete CodeMirror editor interface.

/**
 * Main CodeMirror React component with full configuration support
 * @param props - Component configuration and event handlers
 * @param ref - Reference object for imperative API access
 * @returns JSX element containing the CodeMirror editor
 */
declare const ReactCodeMirror: React.ForwardRefExoticComponent<
  ReactCodeMirrorProps & React.RefAttributes<ReactCodeMirrorRef>
>;

export default ReactCodeMirror;

Usage Examples:

import React from "react";
import CodeMirror from "@uiw/react-codemirror";
import { javascript } from "@codemirror/lang-javascript";
import { oneDark } from "@codemirror/theme-one-dark";

// Basic usage
function BasicEditor() {
  const [code, setCode] = React.useState("console.log('Hello World');");
  
  return (
    <CodeMirror
      value={code}
      onChange={(value) => setCode(value)}
      extensions={[javascript()]}
    />
  );
}

// Advanced configuration
function AdvancedEditor() {
  const [code, setCode] = React.useState("");
  const editorRef = React.useRef();
  
  const handleChange = React.useCallback((val, viewUpdate) => {
    setCode(val);
    console.log('Changed:', val);
  }, []);
  
  const handleStatistics = React.useCallback((stats) => {
    console.log('Stats:', stats.lineCount, 'lines');
  }, []);
  
  return (
    <CodeMirror
      ref={editorRef}
      value={code}
      height="400px"
      minHeight="200px"
      theme={oneDark}
      placeholder="Type your code here..."
      autoFocus
      indentWithTab
      basicSetup={{
        lineNumbers: true,
        highlightActiveLine: true,
        bracketMatching: true,
      }}
      extensions={[javascript({ jsx: true })]}
      onChange={handleChange}
      onStatistics={handleStatistics}
      onCreateEditor={(view, state) => {
        console.log('Editor created:', view);
      }}
    />
  );
}

Component Props

Complete props interface for the ReactCodeMirror component.

interface ReactCodeMirrorProps
  extends Omit<EditorStateConfig, 'doc' | 'extensions'>,
    Omit<React.HTMLAttributes<HTMLDivElement>, 'onChange' | 'placeholder'> {
  /** Value of the editor content */
  value?: string;
  
  /** Editor dimensions */
  height?: string;
  minHeight?: string;
  maxHeight?: string;
  width?: string;
  minWidth?: string;
  maxWidth?: string;
  
  /** Focus behavior */
  autoFocus?: boolean;
  
  /** Placeholder content when editor is empty */
  placeholder?: string | HTMLElement;
  
  /** Theme configuration - 'light', 'dark', 'none', or custom Extension */
  theme?: 'light' | 'dark' | 'none' | Extension;
  
  /** Basic setup configuration */
  basicSetup?: boolean | BasicSetupOptions;
  
  /** Edit behavior */
  editable?: boolean;
  readOnly?: boolean;
  indentWithTab?: boolean;
  
  /** Event handlers */
  onChange?(value: string, viewUpdate: ViewUpdate): void;
  onStatistics?(data: Statistics): void;
  onUpdate?(viewUpdate: ViewUpdate): void;
  onCreateEditor?(view: EditorView, state: EditorState): void;
  
  /** Extensions and configuration */
  extensions?: Extension[];
  root?: ShadowRoot | Document;
  initialState?: {
    json: any;
    fields?: Record<string, StateField<any>>;
  };
}

Component Reference

Reference object returned by the component for imperative API access.

interface ReactCodeMirrorRef {
  /** Reference to the container DOM element */
  editor?: HTMLDivElement | null;
  /** Current CodeMirror editor state */
  state?: EditorState;
  /** Current CodeMirror editor view */
  view?: EditorView;
}

Usage Example:

import React from "react";
import CodeMirror from "@uiw/react-codemirror";

function EditorWithRef() {
  const editorRef = React.useRef();
  
  const focusEditor = () => {
    if (editorRef.current?.view) {
      editorRef.current.view.focus();
    }
  };
  
  const getEditorContent = () => {
    if (editorRef.current?.state) {
      return editorRef.current.state.doc.toString();
    }
    return "";
  };
  
  return (
    <div>
      <button onClick={focusEditor}>Focus Editor</button>
      <button onClick={() => console.log(getEditorContent())}>
        Log Content
      </button>
      <CodeMirror
        ref={editorRef}
        value="// Initial code"
        height="200px"
      />
    </div>
  );
}

State Serialization

Support for persisting and restoring editor state using JSON serialization.

Usage Example:

import React from "react";
import CodeMirror from "@uiw/react-codemirror";
import { historyField } from "@codemirror/commands";

const stateFields = { history: historyField };

function PersistentEditor() {
  const [value, setValue] = React.useState(
    localStorage.getItem('editorValue') || ''
  );
  
  const serializedState = localStorage.getItem('editorState');
  
  const handleChange = (val, viewUpdate) => {
    setValue(val);
    localStorage.setItem('editorValue', val);
    
    // Save state including history
    const state = viewUpdate.state.toJSON(stateFields);
    localStorage.setItem('editorState', JSON.stringify(state));
  };
  
  return (
    <CodeMirror
      value={value}
      initialState={
        serializedState
          ? {
              json: JSON.parse(serializedState),
              fields: stateFields,
            }
          : undefined
      }
      onChange={handleChange}
    />
  );
}

Install with Tessl CLI

npx tessl i tessl/npm-uiw--react-codemirror

docs

extensions.md

hook-api.md

index.md

main-component.md

themes.md

utilities.md

tile.json