Search code examples
javascriptreactjsace-editor

Know where the cursor is in the text using AceEditor in ReactJS


I am creating a code editor and now I would like to know what is the position of the cursor is in the Ace Editor text.

This is the code of component of code editor:

import React, {Component} from 'react';
import AceEditor from 'react-ace';
import 'brace/mode/javascript';
import 'brace/theme/monokai';
import 'brace/ext/language_tools';

class EditorCodeEditor extends Component {
  onChange = e => {
    // Here  I want show for console the position of cursor
    Something like this? -> console.log(this.refs.ace.editor.focus);
  };

  render() {
    return (
      <div>
        <AceEditor
          mode="javascript"
          theme="monokai"
          name="blah2"
          onChange={this.onChange}
          fontSize={14}
          showPrintMargin={true}
          showGutter={true}
          highlightActiveLine={true}
          value="I AM AN EDITOR"
          ref='ace'
          focus={true}
          cursorStart={1}
          editorProps={{$blockScrolling: true}}
          style={{width: '100%', height: '400px'}}
          setOptions={{
            enableBasicAutocompletion: false,
            enableLiveAutocompletion: true,
            enableSnippets: true,
            showLineNumbers: true,
            tabSize: 2
          }} />
      </div>
    );
  }
}

export default EditorCodeEditor;

The problem is when I use ref='ace' in AceEditor label, it returns the error: Using string literals in ref attributes is deprecated. (react/no-string-refs) and the same with this.refs into onChange function.

Any idea for this? Thanks for your help.


Solution

  • ref prop refers to the DOM node. And can be accessed via the following code:

    ref={c => { this.ace = c; }}
    

    For getting the position of the cursor, AceEditor has an onCursorChange prop that you can use.

    onCursorChange(selection) {
      const cursorPosition = selection.getCursor();
    }