uiwjs / react-codemirror

CodeMirror 6 component for React. @codemirror https://uiwjs.github.io/react-codemirror/
https://uiwjs.github.io/react-codemirror/
MIT License
1.65k stars 132 forks source link

Controlled JSON editor issues #505

Closed vdemcak closed 1 year ago

vdemcak commented 1 year ago

Hello, I am currently facing several issues with my React component that incorporates a JSON editor. The problems I am encountering include:

After doing some troubleshooting, I've found that the issue lies in the component being controlled. My question is, should I only pass its value initially?

Thanks.

Here is the code:

export const CodeEditor = ({
  label,
  placeholder,
  value,
  onChange,
  className,
}: {
  label: string;
  placeholder: string;
  value: { [key: string]: any };
  onChange?: (e: any) => void;
  className?: string;
}) => {
  return (
    <div className={className}>
      <label
        htmlFor={`input-${label.toLowerCase().replace(/\s/g, "-")}`}
        className="text-sm font-medium text-gray-900 dark:text-white">
        {label}
      </label>
      <CodeMirror
        id={`input-${label.toLowerCase().replace(/\s/g, "-")}`}
        className="foo"
        placeholder={placeholder}
        value={JSON.stringify(value, null, 2)}
        extensions={[json(), linter(jsonParseLinter())]}
        theme={tokyoNightStorm}
        onChange={onChange}
        maxHeight="60dvh"
      />
    </div>
  );
};

And here is the sample usage:



const Tab = ({ initialData }: { initialData: { [key: string]: any } }) => {
  const [alteredData, setAlteredData] = useState({});

  return (
    <>
       // Various inputs
        <CodeEditor
          className="col-span-2"
          label="Schema data"
          placeholder="{}"
          value={alteredData.data ?? initialData.data}
          onChange={(value) => setAlteredData({ ...alteredData, data: JSON.parse(value) })}
        />
    </>
  );
};```
jaywcjlove commented 1 year ago

@vdemcak https://codesandbox.io/embed/react-codemirror-example-codemirror-6-https-github-com-uiwjs-react-codemirror-issues-505-qjiexb?fontsize=14&hidenavigation=1&theme=dark

import React, { useState } from "react";
import CodeMirror from "@uiw/react-codemirror";
import { json } from "@codemirror/lang-json";

export default function App() {
  const [value, setValue] = useState("{\n  a:123\n}");
  const onChange = React.useCallback((value, viewUpdate) => {
    setValue(value);
  }, []);
  return (
    <div>
      <CodeMirror
        value={value}
        height="200px"
        theme="dark"
        extensions={[json()]}
        onChange={onChange}
      />
      <pre>{value}</pre>
    </div>
  );
}