Using Ace Editor With React

React is a modern front end framework, and Ace editor is a popular javascript based code editor. However, things can get complicated in the process of integrating the two since Ace editor is not designed to work with react. “brace”, the browserify compatible version of Ace editor, and “react-ace”, the “brace” editor embedded in a react component, can be used to smooth the process. I noted down the procedure as follows:

In the project folder, install the node version of Ace editor “brace”, and the “react-ace” package that wrap the “brace” editor as a react component:

npm install brace --save
npm install react-ace --save

require the “brace” and “react-act” packages, together with a “sh” syntax highlighting feature and “chrome” theme from “brace” package:

var brace = require('brace');
var AceEditor = require('react-ace');
require('brace/mode/sh');
require('brace/theme/chrome');

inside the component, return the editor in for rendering:

<AceEditor
  mode="sh"
  theme="chrome"
  name="code"
  width="100%"
  maxLines={50}
  ref="ace"
  fontSize={18}
  value="#type your code here"
  editorProps={{$blockScrolling: Infinity}}
  onLoad={(editor) => {
    editor.focus();
    editor.getSession().setUseWrapMode(true);
  }}
/>

There are two ways to address auto focusing and line wrapping: either by receiving a parameter from onLoad event and call the ace editor native methods (as shown), or by setting a ref="ace" attribute within the AceEditor tag, and then call method like this.refs.ace.editor.focus at “componentDidMount” lifecycle.

Also, setting width: 100% will allow the editor scale with the container, however, setting

height: 100%

will just disable the editor. The work around would be setting a large value of maxLines (for example: 500) and add

editorProps={{$blockScrolling: Infinity}}

attribute to the editor.

Ace editor will allow performing undo actions until the editor is in it’s original empty state, even though the content of the editor is loaded immediately when the component initialize. To fix this, remove the undo history right after the component mounts:

var undo_manager = this.refs.ace.editor.getSession().getUndoManager();
undo_manager.reset();
this.refs.ace.editor.getSession().setUndoManager(undo_manager);


2 thoughts on “Using Ace Editor With React”

  1. Marvan n says:

    Did worked

    1. Anbo Zhou says:

      Glad to hear!

Leave a Reply

Your email address will not be published. Required fields are marked *