How to use CodeMirror in Nextjs?
You have two options when it comes to embedding a code editor in your nextjs application. One is Codemirror and the other is Monaco Monaco Editor.
Monaco Editor is famous because it is actually what vscode uses for its text editor. As you know, the famous one has so many features and with so many features, it makes the bundle too big.
Although codemirror is the old one, it is perfect for embedding a text editor in the browser when a simple and minimalistic editor is needed. My two side projects use this text editor because it is simple and lightweight.
Install
Let's see how you can embed Codemirror
into your nextjs application. Let's install the dependency first.
npm install --save codemirror
Import css
And don't forget to import the css file inside file pages/_app.js
.
import 'codemirror/lib/codemirror.css'
Load setup inside useEffect
Since the Codemirror
work with html dom let's assign ref
instance to textarea that we are going to place the editor.
import { useEffect, useRef } from 'react'
...
const codeMirrorRef = useRef()
...
Then load inside function useEffect
like this. We load it here because the Codemirror
is only work on browser so this mean we can't do server side rendering.
useEffect(() => {
require('codemirror/mode/markdown/markdown')
const CodeMirror = require('codemirror')
const instance = CodeMirror.fromTextArea(codeMirrorRef.current, {
lineNumbers: false,
lineWrapping: true,
mode: "text/x-markdown"
})
}, [])
Pass the ref to view
Then just assign the codeMirrorRef
to the textarea, everything will work like a magic.
return (
<section>
<textarea ref={codeMirrorRef}></textarea>
</section>
)
Styling
Let's explore how we can styling `Codemirror
Custom Language
Codemirror
come with a lot of code formating, if you want for example change the editor to format javascript code you just need to import the library like this.
useEffect(() => {
require('codemirror/mode/markdown/markdown')
...
const instance = CodeMirror.fromTextArea(codeMirrorRef.current, {
...
mode: "javascript"
})
...
Custom theme
If you need change the theme just import the css to file pages/_app.js
like this. There's several theme available in Codemirror
see from the official website here.
import 'codemirror/theme/material.css'
And update the configuration like this.
useEffect(() => {
...
const instance = CodeMirror.fromTextArea(codeMirrorRef.current, {
...
theme: "material"
})
...
Size
So if you need the text editor to be full height and full width set the size like this.
useEffect(() => {
...
const instance = CodeMirror.fromTextArea(codeMirrorRef.current, {
...
})
instance.setSize("100%", "100%")
Here's example from my side project using codemirror Note and JSON Formatter.