Giter Club home page Giter Club logo

react-codemirror's Introduction

Codemirror

The excellent CodeMirror editor as a React.js component.

Demo & Examples

Live demo: JedWatson.github.io/react-codemirror

To build the examples locally, run:

npm install
npm start

Then open localhost:8000 in a browser.

Installation

The easiest way to use codemirror is to install it from NPM and include it in your own React build process (using Browserify, Webpack, etc).

You can also use the standalone build by including dist/react-codemirror.js in your page. If you use this, make sure you have already included React, and it is available as a global variable.

npm install react-codemirror --save

Usage

Require the CodeMirror component and render it with JSX:

var React = require('react');
var CodeMirror = require('react-codemirror');

var App = React.createClass({
	getInitialState: function() {
		return {
			code: "// Code",
		};
	},
	updateCode: function(newCode) {
		this.setState({
			code: newCode,
		});
	},
	render: function() {
		var options = {
			lineNumbers: true,
		};
		return <CodeMirror value={this.state.code} onChange={this.updateCode} options={options} />
	}
});

React.render(<App />, document.getElementById('app'));

Include the CSS

Ensure that CodeMirror's stylesheet codemirror.css is loaded.

If you're using LESS (similar for Sass) you can import the css directly from the codemirror package, as shown in example.less:

@import (inline) "./node_modules/codemirror/lib/codemirror.css";

If you're using Webpack with the css loader, you can require the codemirror css in your application instead:

require('codemirror/lib/codemirror.css');

Alternatively, you can explicitly link the codemirror.css file from the CodeMirror project in your index.html file, e.g <link href="css/codemirror.css" rel="stylesheet">.

Methods

  • focus focuses the CodeMirror instance
  • getCodeMirror returns the CodeMirror instance, available .

You can interact with the CodeMirror instance using a ref and the getCodeMirror() method after the componentDidMount lifecycle event has fired (including inside the componentDidMount event in a parent Component).

Properties

  • autoFocus Boolean automatically focuses the editor when it is mounted (default false)
  • autoSave Boolean automatically persist changes to underlying textarea (default false)
  • className String adds a custom css class to the editor
  • codeMirrorInstance Function provides a specific CodeMirror instance (defaults to require('codemirror'))
  • defaultValue String provides a default (not change tracked) value to the editor
  • name String sets the name of the editor input field
  • options Object options passed to the CodeMirror instance
  • onChange Function (newValue) called when a change is made
  • onCursorActivity Function (codemirror) called when the cursor is moved
  • onFocusChange Function (focused) called when the editor is focused or loses focus
  • onScroll Function (scrollInfo) called when the editor is scrolled
  • preserveScrollPosition Boolean=false preserve previous scroll position after updating value
  • value String the editor value

See the CodeMirror API Docs for the available options.

Using Language Modes

Several language modes are included with CodeMirror for syntax highlighting.

By default (to optimise bundle size) all modes are not included. To enable syntax highlighting:

  • install the codemirror package dependency (in addition to react-codemirror)
  • require the language modes you wish to make available after you require react-codemirror itself
  • set the mode option in the options object
var React = require('react');
var CodeMirror = require('react-codemirror');
require('codemirror/mode/javascript/javascript');
require('codemirror/mode/xml/xml');
require('codemirror/mode/markdown/markdown');

<CodeMirror ... options={{
	mode: 'javascript',
}} />

See the example source for a reference implementation including JavaScript and markdown syntax highlighting.

License

Copyright (c) 2016 Jed Watson. MIT Licensed.

react-codemirror's People

Contributors

alexdmiller avatar anachang-lr avatar codyreichert avatar defunctzombie avatar dpickett avatar fastdivision avatar hatlen avatar jedwatson avatar k15a avatar kmsheng avatar lachenmayer avatar longouyang avatar ovidiuch avatar sapegin avatar stepzhou avatar steveluscher avatar stuhlmueller avatar thealjey avatar timnew avatar vslinko 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  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  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

react-codemirror's Issues

Consider renaming Codemirror.js to Codemirror.jsx

I'm using webpack, because Codemirror.js extension is js but it contains JSX code, I need to pipe node_modules through babel. Maybe consider renaming this file to .jsx so the webpack config can ignore .js files in node_modules.

Standalone version looks for ReactDOM common.js module.

React is handled correctly, but not ReactDOM.

Source Code

// line 9545 Looks for stand-alone version of React
var React = (typeof window !== "undefined" ? window['React'] : typeof global !== "undefined" ? global['React'] : null);

// line 9546 Looks for commonjs module of ReactDOM
var ReactDOM = require('react-dom');

ES6 compatibility

I'm trying to use react-codemirror in my ES6 project but it fails.

Importing it that way:

import CodeMirror from 'react-codemirror';

Getting the following error:

[0] ./~/react-codemirror/src/codemirror.js
[0] Module parse failed: app/node_modules/react-codemirror/src/codemirror.js Unexpected token (76:3)
[0] You may need an appropriate loader to handle this file type.
[0] SyntaxError: Unexpected token (76:3)
...
[0]  @ ./~/react-codemirror/lib/Codemirror.js 20:42-63

Am I doing something wrong or is the project not compatible yet?

Invariant Violation: addComponentAsRefTo

I've put react-codemirror to my project just almost the same as it described in example:

var JSONBrowserPage = React.createClass({
    getInitialState: function(){
        return {
            options: {
                lineNumbers: true,
                mode: {name: "javascript", json: true}
            };
        };
    },

    render: function(){
        return (
            <Codemirror value={this.props.json} options={this.state.options}/>
        );
    }
});

and got next error:
Uncaught Error: Invariant Violation: addComponentAsRefTo(...): Only a ReactOwner can have refs. This usually means that you're trying to add a ref to a component that doesn't have an owner (that is, was not created inside of another component's render method). Try rendering this component inside of a new top-level component which will hold the ref.

When multiple Codemirror components exist on a page, only one can change the language

I have a page that renders multiple instances of this component:

import React, { PropTypes, Component } from 'react'
import CodeMirror from 'react-codemirror'
import 'codemirror/mode/jsx/jsx'
import 'codemirror/mode/javascript/javascript'
import 'codemirror/mode/ruby/ruby'

export class Snippet extends Component {
  static propTypes = {
    language: PropTypes.object,
    text: PropTypes.object
  }

  handleChange(text) {
    this.props.text.onChange(text)
  }

  changeLanguage(e) {
    this.props.language.onChange(e.target.value)
  }

  render() {
    return (
      <div>
        <select value={this.props.language.value} onChange={::this.changeLanguage}>
          <option value='jsx'>JSX</option>
          <option value='javascript'>JavaScript</option>
          <option value='ruby'>Ruby</option>
        </select>
        <CodeMirror options={{ mode: this.props.language.value, theme: 'erlang-dark' }} value={this.props.text.value} onChange={::this.handleChange} />
      </div>
    )
  }
}

It renders one for each entry in an array. The very bottom instance works perfectly. When I change my selection in the language dropdown, I can see the highlighting change as I expect. But all instances above the bottom instance reflect no change when I change their corresponding dropdown select.

There are no errors whatsoever. The CodeMirror instances seem to just be quietly ignoring the language change.

NPM sometimes causes two copies of codemirror.

I ran into a confusing issue where the <Codemirror/> component was loading its own copy of codemirror and my custom implementation of was looking for modes and addons in another directory. This caused my addons to not apply correctly.
If I went in and manually deleted the lower copy of codemirror from the node_modules folder everything was okay again.

node_modules/
├── codemirror/
...
└── react-codemirror/
      └── node_modules/
            └── codemirror/

Not sure if this fixable or just a quirk of version mismatches in npm. Some info in the readme might be helpful for debugging.

Server-Side Rendering?

Any thoughts on how we could integrate this with server-side rendering?

React-code-mirror has a nice approach of simply generating a textarea with the content and then having codemirror hot-load over it once on the client.

Using Codemirror Addons

I'd like to take advantage of the Placeholder addon. This requires adding a placeholder attribute to the textarea. Can this react-codemirror component be extended to include the ability to add attributes directly to the textarea element that gets generated?

ReferenceError: navigator is not defined

ReferenceError: navigator is not defined W20161022-17:29:38.375(-4)? (STDERR) at /Users/mattmacpherson/Code/project/node_modules/codemirror/lib/codemirror.js:24:19 W20161022-17:29:38.375(-4)? (STDERR) at userAgent (/Users/mattmacpherson/Code/project/node_modules/codemirror/lib/codemirror.js:12:22) W20161022-17:29:38.376(-4)? (STDERR) at Object.<anonymous> (/Users/mattmacpherson/Code/project/node_modules/codemirror/lib/codemirror.js:17:3) W20161022-17:29:38.376(-4)? (STDERR) at Module._compile (module.js:409:26) W20161022-17:29:38.376(-4)? (STDERR) at Object.Module._extensions..js (module.js:416:10) W20161022-17:29:38.376(-4)? (STDERR) at Module.load (module.js:343:32) W20161022-17:29:38.377(-4)? (STDERR) at Module.Mp.load (/Users/mattmacpherson/.meteor/packages/babel-compiler/.6.9.1_1.15j1r1l++os+web.browser+web.cordova/npm/node_modules/reify/node/runtime.js:16:23) W20161022-17:29:38.377(-4)? (STDERR) at Function.Module._load (module.js:300:12) W20161022-17:29:38.378(-4)? (STDERR) at Module.require (module.js:353:17) W20161022-17:29:38.378(-4)? (STDERR) at require (internal/module.js:12:17)

I only get this error when requiring modes:

require('codemirror/mode/javascript/javascript'); require('codemirror/mode/xml/xml'); require('codemirror/mode/markdown/markdown');

Hints?

Hello.
Thanks for this!

Is it possible to use code hints?
If yes, could you provide an example?

Thanks!

lint addon is not working

I've been trying to add javascript-lint gutter markers to my code editor and I haven't been getting anywhere. I am importing the lint.js and javascript-lint.js files from codemirror like I assume I am supposed to do. I have also added the lint and gutter options to my options object like I've also seen. I am getting everything to work properly except the lint gutter markers. Below is the code I am using to make the code editor and the result after I have bundled the code and am running it on my website. Am I doing something wrong? Help is much appreciated, thanks!

Javascipt File

import React from 'react';
import CodeMirror from 'react-codemirror';
const isBrowser = typeof window !== 'undefined';
isBrowser ? function(){
  require('codemirror/mode/javascript/javascript');
  require('codemirror/addon/lint/lint');
  require('codemirror/addon/lint/javascript-lint');
}() : undefined;

import _ from 'underscore';

class CodeEditor extends React.Component{
  constructor(props){
    super(props);
    
    this.state = {
      code: this.props.children,
      output: "",
      theme: 'tomorrow-night-bright',
      error: ""
    };
  }
  updateCode(e) {
    this.setState({
      code: e
    });
  }
  toggleTheme() {
    let newTheme = this.state.theme == 'tomorrow-night-bright' ? 'default' : 'tomorrow-night-bright';
    this.setState({
      theme: newTheme
    });
  }
  evalCode() {
    let newOutput = "";
    let code = this.state.code.replace(/\/\*[\s\S]*?\*\/|([^\\:]|^)\/\/.*$|(<script>)|eval|XMLHttpRequest|document\.write/gm,"");
    try{
      newOutput = (() => {return eval(code)})();
    } catch(e) {
      newOutput = "";
    }
    let error = "";
    if(this.props.test) {
      let include = this.props.test.include;
      let notInclude = this.props.test.notInclude || [];
      let expectedOutput = this.props.test.output;
      include = include.map(item => code.indexOf(item).toString());
      notInclude = notInclude.map(item => code.indexOf(item).toString());
      
      if(include.indexOf("-1") != -1) {
        console.log("You did not use the necessary items in this exercise.");
        error = <div className="editorError">You did not use the necessary items in this exercise.</div>;
      } else if(notInclude.indexOf("-1") == -1) {
        console.log("You still have some of following keywords in your program: " + notInclude);
        error = <div className="editorError">You still have some of following keywords in your program: {notInclude}</div>;
      } else if(_.isEqual(newOutput,expectedOutput) === false) {
        console.log("Oops, it looks like your output does not match expected output.");
        error = <div className="editorError">Oops, it looks like your output does not match expected output.</div>;
      } else {
        error = <div className="editorSuccess">Good Job!</div>;
      }
    }
    this.setState({
      output: newOutput,
      error: error
    });
  }
  render() {
    let outputClass = 'editorOutput';
    let buttonsClass = 'editorButtons';
    if(this.state.theme == 'default'){
      outputClass = 'editorOutput lightEditorOutput';
      buttonsClass = 'editorButtons lightEditorButtons';
    }
    
    let options = {
      lineNumbers: true,
      mode: 'javascript',
      theme: this.state.theme,
      scrollbarStyle: 'null',
      lineWrapping: true,
      lint: true,
      gutters: [
        'CodeMirror-lint-markers',
      ]
      
    };
    return (
      <div className="editorContainer">
      <div className={buttonsClass}>
        <button onClick={this.evalCode.bind(this)}>Run</button>
        <button onClick={this.toggleTheme.bind(this)}>Toggle Light/Dark</button>
        {this.state.error}
      </div>
      <CodeMirror ref="editor" className="editor" value={this.state.code} onChange={this.updateCode.bind(this)} options={options}/>
      <div className={outputClass}>
        <small style={{color: "red",fontSize: "10px"}}>Output</small><br/>{JSON.stringify(this.state.output)}
      </div>
      </div>
    );
  }
}

export default CodeEditor;

Result
Editor image

Potentially implement autoFocus

I was just wondering if you had any plans of implementing the autoFocus property. If this was set to true, it would focus inside code mirror, if it was false (default) it would not.

I know I can call .focus, but I am trying to refrain from using any dom or refs.

[ Question ] Doesn't show up anything ( blank ), is my configuration wrong ?

This is my first time using it and trying to setup a basic version in order for it to show up, the following is my setup, let me know if I did something wrong, thanks.

import React, { PropTypes } from 'react';
import { default as CodeMirror } from 'react-codemirror';
require('codemirror/mode/javascript/javascript');

const codeTypes = {
  javascript: 'var welcome = {\n\tmode: "javascript"\n};'
};

And the following is the render function

  render() {
    const props = this.props;
    const options = {
      lineNumbers: true,
      readOnly: false,
      mode: 'javascript'
    };

    return (
        <div>
          <CodeMirror
            ref="editor"
            value={props.code}
            onChange={this.updateCode}
            options={options}
            interact={this.interact}
          />
        </div>
    );
  }

And I do see the code generated, but my screen is blank, am I missing something ?

screen shot 2016-08-14 at 11 11 48 pm

propType for codeMirrorInstance should be function

Now that #33 is merged, I'm trying to pass in my own CodeMirror instance to the component but I'm getting a warning:

Warning: Failed propType: Invalid prop `codeMirrorInstance` of type `function` supplied to `CodeMirror`, expected `object`. Check the render method of `CodeEditor`.

I think the propType for codeMirrorInstance should be switched from object to function, because require('codemirror') actually returns a function. (In particular, it's a function with properties attached, which is object-like, but not a true object).

this.valueChanged doesn't exists

When trying to use this component I get:

"Warning: Failed propType: You provided a value prop to a form field without an onChange handler. This will render a read-only field. If the field should be mutable use defaultValue. Otherwise, set either onChange or readOnly. Check the render method of CodeMirror."

Looking at the source:

<textarea ref="codemirror" name={this.props.path} value={this.props.value} onChange={this.valueChanged} autoComplete="off" />

the function valueChanged is not found elsewhere.

Testing with selenium

I've been stuck trying to test this component with webdriver.io for days now. Has anyone successfully been able to do this??

Expose CodeMirror library

I'm trying to use Firebase's Firepad with this component. Firepad is expecting a global CodeMirror object, which it doesn't find unless I include the library separately. Perhaps it is a given that this conflicts with this component? Is there a way to expose the CodeMirror library within a component, so that it is available to Firepad? Apologies if this is the wrong place to ask this.

differentiate onChange vs. manual input?

Hi there! I would just like to start by saying thanks! React-Codemirror has been awesome. Sometimes I wish instead of bug reports there was a thing on github for "appreciation reports".

Anyway, a thing I just ran into is that it seems the onChange handler gets called both when a user is editing a codemirror and also when changing the value from React (which I believe uses cm.setValue()). I was wondering if it's worth differentiating those two cases in this library. Maybe it isn't, but it might at least be specified in the docs. Either way, I'm going to figure out a way around it for my use case so that I can tell when a user is doing something in the text field vs when my stuff is re-rendering a value to the codemirror instance.

How could using addon : fold

I found fold demo here: https://codemirror.net/demo/folding.html

And I try this:

import markdown-fold.js && foldgutter.css;

const options = {
    mode: "gfm",
    lineNumbers: true,
    lineWrapping: true,
    extraKeys: {"Ctrl-Q": function(cm){ cm.foldCode(cm.getCursor()); }},
    foldGutter: true,
    gutters: ["CodeMirror-linenumbers", "CodeMirror-foldgutter"]
}

nothing happend...
I'm new here...What should I do next? Thanks...

How to simulate `change` event?

I'm writing a unit test with mocha to test that my CodeMirror calls this.props.onChange method.
Normally, I use TestUtils.Simulate (from react-addons-test-utils) to simulate change event on input or textarea. But, for CodeMirror, it does not respond to such event. (I tried with every css class selector prefixed with CodeMirror.)

Outside mocha, my CodeMirror works fine. It calls the this.props.onChange but I'd like to create a unit test to cover this case.

Thanks you in advance.

Codemirror syntax highlighting doesn't seem to work

First of all, thanks for putting the work into making CodeMirror work with React. I have it working great EXCEPT the syntax highlighting just doesn't work. I included the necessary library modes (ie: Javascript, PHP) and theme but the Syntax doesn't get highlighted. When I view the live DOM, I don't see any of the markdown that triggers the syntax colors (like cm-tag, etc...). Has anyone else experienced this?

aXe audit: Form elements must have labels

Running the aXe: the accesibility engine chrome extension yields a critical violation: Form elements must have labels.

The target in question is <textarea ref="textarea" ... https://github.com/JedWatson/react-codemirror/blob/master/src/Codemirror.js#L85

Summary:
Fix any of the following:

  • aria-label attribute does not exist or is empty
  • aria-labelledby attribute does not exist, references elements that do not exist or references elements that are empty or not visible
  • Form element does not have an implicit (wrapped)
  • Form element does not have an explicit
  • Element has no title attribute or the title attribute is empty

Re-setting options on an existing instance can have side effects

I've found that react-codemirror seems incompatible with proper usage of the lint add-on to CodeMirror.

The way to activate linting is to set it as an option, e.g.

CodeMirror.fromTextArea([…], {
  lint: {
    predef: ["window"]
  }
});

lint's default behavior is to respond to onChange events (debounced and on a 500ms delay), but when it's first initialized, it runs immediately on the current editor value. react-codemirror's approach to setting all of the options whenever the component updates effectively causes lint to fire on every editor change (with no delay) because setting the lint option re-initializes it, even if the option provided is the same.

I have a proof-of-concept that addresses this problem by comparing the editor's existing option values to the new option values on each update, and only setting each option if it's different. But, I'm waiting to hear about #49 because the underlying bug behind that pull request prevents options from being applied correctly to multiple instances of CodeMirror.

The approach I had in mind is a bit of a kludge, but I think JSON.stringify would suffice as a way to compare option values quickly:

setCodeMirrorOptionIfChanged: function(optionName, newValue) {
    var oldValue = this.codeMirror.getOption(optionName);
    if (JSON.stringify(oldValue) !== JSON.stringify(newValue)) {
        this.codeMirror.setOption(optionName, newValue);
    }
},

require('codemirror') loads react-codemirror component

I've tried to embed react-codemirror into the app as described in the example, but faced strange issue.
I got an error TypeError: CM.fromTextArea is not a function.

After some investigation, I found that react-codemirror loads itself here https://github.com/JedWatson/react-codemirror/blob/master/lib/Codemirror.js#L6

CM contains CodeMirror react component.

I'm bundling project with webpack and babel. Result bundle contains 2 equal module IDs 648 and 649, and 649 depends on 648, react-codemirror both.

Here is a sample of webpack config:

module.exports = {
  context: join(__dirname, '/src'),

  entry: {
    app: [
      'babel-polyfill',
      './scripts/master',
      './index.html'
    ]
  },

  output: {
    path: join(__dirname, '/dist'),
    filename: '[name].js'
  },

  debug: true,

  devtool: null,

  module: {
    loaders: [
      {
        test: /(\.js|\.jsx)$/,
        include: [
          join(__dirname, 'src'),
          join(__dirname, 'node_modules/react-codemirror')
        ],
        loader: 'babel'
      },
      {
        test: /(\.scss|\.css)$/,
        loader: ExtractTextPlugin.extract('style', 'css?sourceMap&modules&importLoaders=1&' +
          'localIdentName=[name]__[local]___[hash:base64:5]!postcss!sass?sourceMap!toolbox')
      },
    ]
  },
  resolve: {
    extensions: ['', '.js', '.jsx', '.json', '.scss', '.css'],
    modulesDirectories: [
      'node_modules',
      'src/scripts',
      'src'
    ]
  },

};

How can I specify the height?

I've tried putting the following in options but none seem to make any change.

"height": "100%"
"height": "800px"
"height": "auto"

How can I set the height?

thanks

Uncaught TypeError: Cannot read property 'setOption' of undefined

Hi

I receive Uncaught TypeError: Cannot read property 'setOption' of undefined, which happens in componentWillReceiveProps at line 50.
this.codeMirror.setOption(optionName, nextProps.options[optionName]);

For some reason, it seems that componentWillReceiveProps triggers before componentDidMount, so this.codeMirror is not yet defined.

The event also triggers after componentDidMount, though.

Linenumber rendering issue

Because all other issues regarding this topic were closed, I opened this new issue.

This is my CodeMirror instance:
codemirror.txt

I am using autorefresh and simplescrollbars.

I recorded the issue I am experiencing:
Video

When starting the editor, the linenumbers look like:
Image

Does not highlight javascript text correctly

If I want to display javascript with react-codemirror it doesn't correctly highlight the code to match the set theme. This is because you need to load the javascript background worker. Something like this:

require('../node_modules/codemirror/mode/javascript/javascript');

debounce(componentWillReceiveProps) breaks with MobX + multiple instances

I just confirmed that when when an observable changes (e.g. @observable myName = ""):

<CodeMirror key="something" value={myName} />
<CodeMirror key="something-else" value={myName} />

Only the last <CodeMirror /> instance updates.

Once I removed debounce from componentWillReceiveProps, everything worked as intended.

Example in repository is not working correctly

I copied the code from react-codemirror/example/src/example.js
I am running:
codemirror .5.12.0
react-codemirror 0.2.5
react 0.14.6
nodejs 5.6.0

Issues I am having:

  1. with line numbers turned off the display has some extra area above the first line with a single character x
x
var component = {
    name: "react-codemirror",
    author: "Jed Watson",
    repo: "https://github.com/JedWatson/react-codemirror"
};
  1. With * line numbers turned on* the menus at the bottom stay left aligned and the text in the editor shifts way right( cannot figure out how much).
x

1
var component = {
2
    name: "react-codemirror",
3
    author: "Jed Watson",
4
    repo: "https://github.com/JedWatson/react-codemirror"
5
};

'''



Line Numbers not rendering to gutter correctly.

Using Browserify.

If I toggle the included css being pointed to the numbers display correctly.

snapshot

Like this:
.CodeMirror-gutter-elt {left: -29px !important}

The line numbers display correctly, after I include the above line of css.

Possibly related areas of code:
https://github.com/JedWatson/react-codemirror/blob/master/lib/Codemirror.js#L23
https://github.com/JedWatson/react-codemirror/blob/master/dist/react-codemirror.js#L677-L678
https://github.com/JedWatson/react-codemirror/blob/master/dist/react-codemirror.js#L1052-L1063

I was also having difficulties with getting extra themes to work as well, since the className was not being appended to the correct elements.

var Editor         = require('./codeeditorview/CodeMirror')
    editorConfig: {
        'mode': 'javascript',
        'theme': 'cm-s-monokai',
        'lineNumbers': true,
    },
<Editor config={ this.items.editorConfig }/>

./codeeditorview/CodeMirror':

'use strict';
var Codemirror = require('react-codemirror');
var Editor = React.createClass({
    getInitialState: function() {
        return {
            code: 'function add(a, b) {\n' +
                  '  return a + b;\n' +
                  '}'
        };
    },
    updateCode: function(newCode) {
        console.log('From the editor',newCode)
        this.setState({
            code: newCode
        });
    },
    render: function() {
      var options = this.props.config
      return (
          <Codemirror value={this.state.code} onChange={this.updateCode} options={options} />
      )
    }
  });

// React.render(<App />, document.getElementById('app'));
module.exports = Editor

Overlay method

How do I do overlays? I want to overlay a mustache syntax highlighting over XML, something similar to this example.

npm distribution has in the src folder a codemirror.js instead of codemirror.jsx

Inside the dist/src folder, now there is a codemirror.js file which contains jsx code.

The problem I have is, I am using webpack to bundle it, but it complains that cannot process this file, cos it is a js file and does not understand the jsx inside. Not sure why it goes there, but it just fails. I managed to fix it and works well, when I change the extension from .js to .jsx. Afterwards everything worked well.

How to use 'command' in codemirror

I want to use save command in codemirror.

like this:

CodeMirror.commands.save = function () {
     alert("Saving");
};

Cant find a way to use this in react-codemirror...

Cannot run the demo app

I tried using react-codemirror in an electron app but it doesn't show the editor at all. So i tried running the demo app in this repo but get the following build error -

Browserify Error { Error: Cannot find module 'browserify-optional' from '/Users/mukeshsoni/Desktop/test/react-codemirror/node_modules/react-dom-polyfill'
    at /Users/mukeshsoni/Desktop/test/react-codemirror/node_modules/resolve/lib/async.js:46:17
    at process (/Users/mukeshsoni/Desktop/test/react-codemirror/node_modules/resolve/lib/async.js:173:43)
    at ondir (/Users/mukeshsoni/Desktop/test/react-codemirror/node_modules/resolve/lib/async.js:188:17)
    at load (/Users/mukeshsoni/Desktop/test/react-codemirror/node_modules/resolve/lib/async.js:69:43)
    at onex (/Users/mukeshsoni/Desktop/test/react-codemirror/node_modules/resolve/lib/async.js:92:31)
    at /Users/mukeshsoni/Desktop/test/react-codemirror/node_modules/resolve/lib/async.js:22:47
    at FSReqWrap.oncomplete (fs.js:123:15)
  stream: 
   Labeled {
     _readableState: 
      ReadableState {
        highWaterMark: 16,
        buffer: [],
        length: 0,
        pipes: [Object],
        pipesCount: 1,
        flowing: true,
        ended: false,
        endEmitted: false,
        reading: true,
        sync: false,
        needReadable: true,
        emittedReadable: false,
        readableListening: false,
        objectMode: true,
        defaultEncoding: 'utf8',
        ranOut: false,
        awaitDrain: 0,
        readingMore: false,
        decoder: null,
        encoding: null,
        resumeScheduled: false },
     readable: true,
     domain: null,
     _events: 
      { end: [Object],
        error: [Object],
        data: [Function: ondata],
        _mutate: [Object] },
     _eventsCount: 4,
     _maxListeners: undefined,
     _writableState: 
      WritableState {
        highWaterMark: 16,
        objectMode: true,
        needDrain: false,
        ending: true,
        ended: true,
        finished: true,
        decodeStrings: true,
        defaultEncoding: 'utf8',
        length: 0,
        writing: false,
        corked: 0,
        sync: false,
        bufferProcessing: false,
        onwrite: [Function],
        writecb: null,
        writelen: 0,
        buffer: [],
        pendingcb: 0,
        prefinished: true,
        errorEmitted: false },
     writable: true,
     allowHalfOpen: true,
     _options: { objectMode: true },
     _wrapOptions: { objectMode: true },
     _streams: [ [Object], [Object] ],
     length: 2,
     label: 'deps' } }
[19:09:56] Browserify Error { Error: Cannot find module 'browserify-optional' from '/Users/mukeshsoni/Desktop/test/react-codemirror/node_modules/react-dom-polyfill'
    at /Users/mukeshsoni/Desktop/test/react-codemirror/node_modules/resolve/lib/async.js:46:17
    at process (/Users/mukeshsoni/Desktop/test/react-codemirror/node_modules/resolve/lib/async.js:173:43)
    at ondir (/Users/mukeshsoni/Desktop/test/react-codemirror/node_modules/resolve/lib/async.js:188:17)
    at load (/Users/mukeshsoni/Desktop/test/react-codemirror/node_modules/resolve/lib/async.js:69:43)
    at onex (/Users/mukeshsoni/Desktop/test/react-codemirror/node_modules/resolve/lib/async.js:92:31)
    at /Users/mukeshsoni/Desktop/test/react-codemirror/node_modules/resolve/lib/async.js:22:47
    at FSReqWrap.oncomplete (fs.js:123:15)
  stream: 
   Labeled {
     _readableState: 
      ReadableState {
        highWaterMark: 16,
        buffer: [],
        length: 0,
        pipes: [Object],
        pipesCount: 1,
        flowing: true,
        ended: false,
        endEmitted: false,
        reading: true,
        sync: false,
        needReadable: true,
        emittedReadable: false,
        readableListening: false,
        objectMode: true,
        defaultEncoding: 'utf8',
        ranOut: false,
        awaitDrain: 0,
        readingMore: false,
        decoder: null,
        encoding: null,
        resumeScheduled: false },
     readable: true,
     domain: null,
     _events: 
      { end: [Object],
        error: [Object],
        data: [Function: ondata],
        _mutate: [Object] },
     _eventsCount: 4,
     _maxListeners: undefined,
     _writableState: 
      WritableState {
        highWaterMark: 16,
        objectMode: true,
        needDrain: false,
        ending: true,
        ended: true,
        finished: true,
        decodeStrings: true,
        defaultEncoding: 'utf8',
        length: 0,
        writing: false,
        corked: 0,
        sync: false,
        bufferProcessing: false,
        onwrite: [Function],
        writecb: null,
        writelen: 0,
        buffer: [],
        pendingcb: 0,
        prefinished: true,
        errorEmitted: false },
     writable: true,
     allowHalfOpen: true,
     _options: { objectMode: true },
     _wrapOptions: { objectMode: true },
     _streams: [ [Object], [Object] ],
     length: 2,
     label: 'deps' } }

I don't know if the problems in electron app usage are also due to browserify errors.

place is not a function

TypeError: place is not a function[Learn More] bundle.js:56747:13

	  if (place) {
	    if (place.appendChild) { place.appendChild(d.wrapper) }
	    else { place(d.wrapper) }
	  }

I'm not sure what's going on here. The else { place(d.wrapper) } line is throwing that error. Is there a specific version of codemirror that's required?

onChange fires when value is changed programatically

onChange is called when the Codemirror component receives a new value when rendering.

Test case: https://gist.github.com/insin/9e507894f3858028c7e5
Live version: http://bl.ocks.org/insin/raw/9e507894f3858028c7e5/

Every call to onChange is alert()-ed, Clicking the "Change value" button changes the value in the component's state.

Just got bit by this using Redux, as updating some state which was being passed to Codemirror resulted in another dispatch firing via onChange, resulting in old state being retained. Worked around it myself by having onChange check if it received the same value as was being used for rendering, but is this behaviour something that's possible to control, or it is a consequence of how Codemirror itself is implemented?

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.