In the last post I created a React component that intercepted and formatted the arguments for console.log and console.error.

In this post I’ll be upgrading from a simple <textarea> to something that is designed to show code.

What Should I Use?

After mulling over a few different options, even considering making something from scratch, I decided that  CodeMirror would be the best fit for short code snippets.

Fortunately, CodeMirror v6 is out and it’s a fantastic opportunity to try it out.

Creating the Editor Component

The editor component will live in src/components/editor/index.tsx. For now, it will be an empty react component.

import React from "react";

export const Editor = () => {
  return <></>;
};

We’ll also need to install some libraries from npm

npm i @codemirror/view @codemirror/state

CodeMirror needs to be attached to a DOM node, so we’ll add it via a ref. We’ll also use a <section> for some added semantics. In the world of TypeScript types, I learned that any HTML element that doesn’t need more than what the base interface provides, like <section>, should use the HTMLElement type.

import React from "react";

export const Editor = () => {
  const editorRef = React.useRef<HTMLElement>(null);
  return <section ref="editorRef"/>;
};

#react #codemirror #typescript #typescript-with-react

Failing to add CodeMirror 6 (and then Succeeding)
5.85 GEEK