Open darkmirrors opened 2 years ago
Codemirror is a stateful editor, so it is not that great for a case you mention. You have to lookup through codemirrors docs, which are not that obvious.
Since this is a controlled component, the value
is already set from outside. So, conceptually, all it takes to reset the value is to trigger setValue()
with whatever new string.
For onChange
function, you want to use useCallback
. It's tricky to type it in one line, so I declare it separately, like this (I ended up using @uiw/react-codemirror
which is more popular, but the gist should be the same here):
import { useState, useCallback } from "react";
import CodeMirror from "@uiw/react-codemirror";
import type { ReactCodeMirrorProps } from "@uiw/react-codemirror";
import { html } from "@codemirror/lang-html";
import { EditorView } from "@codemirror/view";
...
const [inputStr, setInputStr] = useState("");
const onChangeFn: ReactCodeMirrorProps["onChange"] = (value, viewUpdate) => {
setInputStr(value);
};
const onChange = useCallback(onChangeFn, []);
return (
<CodeMirror
className="cm-outer-container"
value={inputStr}
height="200px"
extensions={[html(), EditorView.lineWrapping]}
readOnly={true}
/>
)
I want to reset the editor value externally
When I set
value={value}
, there are two problemsHow to solve this problem?