Samir Zafar
Samir Zafar

Reputation: 66

CodeMirror editor duplicating

So I am trying to insert a code editor into my web application. I am trying to import and add an instance of Codemirror. Everytime I add JSX code for a CodeMirror component it duplicates. Here is my component code.

import { Controlled as ControlledEditor } from "react-codemirror2";
import "codemirror/lib/codemirror.css";
import "codemirror/theme/material.css";
require("codemirror/mode/xml/xml");
require("codemirror/mode/javascript/javascript");

const ProblemSolving = () => {
  return (
    <div className="editor-container">
        <div className="editor-title">
            Hello World
        </div>
        <ControlledEditor
            value="var myVariable = 5"
            options={{
                lineWrapping: true,
                lint: true,
                mode: "javascript",
                lineNumbers: true
            }}  
        />
    </div>
  );
};

export default ProblemSolving;

enter image description here

As you can see in the image there are two editors being renders. one where the default value I set has been entered and another that has a blank empty line. I am not sure why this is happening.

Upvotes: 2

Views: 2034

Answers (2)

Jean-Pierre Novak
Jean-Pierre Novak

Reputation: 1

I had the same issue here.

What I did is I removed the React.StrictMode from my main.tsx file (since I used Vite to create the app) and it started working.

I believe the same should work for CRA

Upvotes: 0

Pintu Singh
Pintu Singh

Reputation: 51

This issue is caused by a new feature in React18: https://reactjs.org/docs/strict-mode.html#ensuring-reusable-state simply removed the editor dom, there should be a more appropriate way.

function App() {
  const editor = useRef()
  const wrapper = useRef()
  const editorWillUnmount = () => {
    editor.current.display.wrapper.remove()
    wrapper.current.hydrated = false
  }
  return (
    <div className="App">
      <CodeMirror
        value='<h1>I ♥ react-codemirror2</h1>'
        ref={wrapper}
        options={{
          mode: 'xml',
          theme: 'material',
          lineNumbers: true
        }}
        onChange={(editor, data, value) => {
        }}
        editorDidMount={(e) => editor.current = e}
        editorWillUnmount={editorWillUnmount}
      />
    </div>
  );
}

Or remove React.StrictMode in index.js

  <React.StrictMode>
    <App />
  </React.StrictMode>

Upvotes: 5

Related Questions