Giter Club home page Giter Club logo

use-codemirror's Introduction

use-codemirror

NPM

Add the excellent CodeMirror editor to your React app with a hook.

๐Ÿ“Œ Supports multiple documents (e.g. for tabbed editors)
๐Ÿ“Œ Built with TypeScript
๐Ÿ“Œ Works with SSR
๐Ÿ“Œ Built-in lazy loading for CodeMirror itself
๐Ÿ“Œ Allows easy access to the underlying instance

Getting started

yarn add use-codemirror

Create your own Editor component by calling useCodeMirror, then passing the returned object's ref to a <pre> containing your initial value.

import { useCodeMirror } from 'use-codemirror'

export function Editor({ className, style, ...options }) {
  let codeMirror = useCodeMirror(options)

  return (
    <StyledCodeMirrorEditor className={className} style={style}>
      <pre ref={codeMirror.ref} className={codeMirror.config.theme}>
        {options.value}
      </pre>
    </StyledCodeMirrorEditor>
  )
}

Then use your Editor:

function App() {
  let [code, setCode] = useState(initialCode)

  return (
      <CodeMirrorEditor
        value={code}
        onChange={setCode}

        // Supports multiple documents with their own history,
        // and automatic syntax highlighting via file extension.
        docName="test.js"

        // Pass config to CodeMirror itself
        config={{
          autoCloseBrackets: false,
        }}
      />
  );
}

See the example directory for a working example.

API

You can pass in the following settings:

interface UseCodeMirrorOptions {
  cursor?: CodeMirror.Position
  doc?: CodeMirror.Doc
  docName?: string
  scroll?: SetScrollOptions
  selection?: { ranges: Array<SetSelectionOptions>; focus?: boolean }
  value: string

  config?: CodeMirror.EditorConfiguration

  onBlur?: () => void
  onChange?: (
    value: string,
    docName: string | undefined,
    changes: CodeMirror.EditorChange[],
    doc: CodeMirror.Doc,
  ) => void
  onCursor?: (data: CodeMirror.Position) => void
  onFocus?: () => void
  onGutterClick?: (lineNumber: number, gutter: string, event: Event) => void
  onScroll?: (scrollInfo: CodeMirror.ScrollInfo) => void
  onSelection?: (data: any) => void
  onViewportChange?: (start: number, end: number) => void

  // Only used on initial run
  importCodeMirror?: () => Promise<any>
  importCodeMirrorAddons?: () => Promise<any>
}

The returned codeMirror object has the following shape:

interface ReactCodeMirror {
  // Pass this to a `<pre>` to turn it into a CodeMirror
  ref: CodeMirrorRefFunction

  // The configuration, with any default settings
  config: CodeMirror.EditorConfiguration

  // The underlying CodeMirror instance
  editor?: CodeMirror.Editor

  focus(): void
}

Acknowledgements

This projects takes a lot of inspiration (and a bit of code) from react-codemirror2.

License

use-codemirror is MIT licensed.

use-codemirror's People

Contributors

jamesknelson avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

use-codemirror's Issues

Example missing

The example directory seems to be linked to another repo that is not available, or something?

How do you get the value of the editor?

I just want to let you know this is a really cool editor. THANKS!

I'm trying to get the value of the editor. The below code works. It shows me the contents of the code editor when I press the button

but when I try to change the stuff in the code editor it gives me this error
"Error: Objects are not valid as a React child (found: object with keys {from, to, text, removed, origin}). If you meant to render a collection of children, use an array instead."

Screenshot of error https://imgur.com/a/8IHTV8F

import React, { useState } from "react";

import { CodeMirrorEditor } from "./CodeMirrorEditor";

import "./../App.css";

function Test() {
  const [content, setContent] = useState("//is this working?");
  const [runCode, setRunCode] = useState(false);

  function run() {
    setRunCode(true);
    console.log(content);
  }

  return (
    <React.Fragment>
      <button onClick={run}>Run</button>
      <CodeMirrorEditor
        id="codeMirror"
        docName="test.js"
        value={content}
        onChange={(editor, data, value) => {
          setRunCode(false);
          setContent(value);
        }}
        config={{
          autoCloseBrackets: true,
          lineNumbers: true,
          viewportMargin: Infinity
        }}
      />

      <div className="Output">
        <pre>{runCode && content}</pre>
      </div>
    </React.Fragment>
  );
}

export default Test;

Suggestion - drop styledcomponents

You're free of course to do as you choose and you're code is nice but my personal preference would be to skip "styled components" and just include a <style> tag. I find styled components to be really indirect and messy when a plain style tag will do the same thing without the additional complexity layer and dependency. Just a suggestion.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.