Hook CodeMirror into your project 🧶

Now as we’ve successfully setup CodeMirror, let us hook the editor into our webpage. CodeMirror actually works on top of a <textarea> element of your web document.

In your document wherever you want the editor to be located insert a <textarea> element like so:

<textarea id=”editor”></textarea>

Now in your javascript file just add:

let cm = new CodeMirror();

This will attach CodeMirror to the first <textarea> element it finds in the document. if you want to attach CodeMirror to a custom <textarea> element instead of the above code insert the following code:

let cm = new CodeMirror.fromTextArea(document.findElementById("editor"));

and Congratulations you have your very own text editor inside your web app! You can configure it in any way you like by passing a configuration object as the second parameter like so:

var cm = new CodeMirror.fromTextArea(document.getElementById("editor"), {lineNumbers: true});

Yes, this one line was enough to provide line numbers to your editor! By now your codemirror editor should somewhat look like this -