Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Editor Duplicating #284

Open
mezplz opened this issue Jun 12, 2022 · 3 comments
Open

Editor Duplicating #284

mezplz opened this issue Jun 12, 2022 · 3 comments

Comments

@mezplz
Copy link

mezplz commented Jun 12, 2022

Hi, I use react-codemirror2 7.2.1 and React 18, I got the editor duplicating. When I use React17, it worked fine. Is there anyway to fix ?

@jdz321
Copy link

jdz321 commented Jun 15, 2022

This issue is caused by a new feature in React18: https://reactjs.org/docs/strict-mode.html#ensuring-reusable-state
I saw this question for a friend, and solved this way. I 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>
  );
}

@undeletable
Copy link

@jdz321 Thanks a lot! This works for me too. I'd like to add a note for the ones who use TypeScript like me: this is not type safe solution, since display and hydrated properties aren't exposed as public properties of the corresponding interfaces. So you'll have either to add type assertions to any for them, or add ignore comment. Sounds dirty, but the whole solution is a hack.

@bilalesi
Copy link

for anyone looking for TS solutions

          editorDidMount={editorElement => {
            (editorRef as React.MutableRefObject<
              codemirror.Editor
            >).current = editorElement;
          }}
          editorWillUnmount={() => {
            const editorWrapper = (editorRef as React.MutableRefObject<
              CodeMirror.Editor
            >).current.getWrapperElement();
            if (editorWrapper) editorWrapper.remove();
            if (wrapperRef.current) {
              (wrapperRef.current as { hydrated: boolean }).hydrated = false;
            }
          }}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants