Search code examples
reactjscodemirrorreact-codemirror

Codemirror shows JSON all on single line


Started a new project using react-codemirror2 and react-jsonschema-form very similar too https://mozilla-services.github.io/react-jsonschema-form/

However when my codemirror editor renders the JSON I am loading all shows on a single line. I have been through the source code of https://mozilla-services.github.io/react-jsonschema-form/ and cannot find anything different from what I have.

enter image description here

My Source code:

    import React, { useEffect, useState } from "react";
import { UnControlled as CodeMirror } from "react-codemirror2";

import "codemirror/lib/codemirror.css";
import "codemirror/theme/material.css";
import "codemirror/mode/javascript/javascript.js";

// components

const CodeEditorContainer = ({ code, onChange }) => {
  const [codeEditorState, setCodeEditorState] = useState();

  useEffect(() => {
    setCodeEditorState(code);
  }, [code]);

  const cmOptions = {
    theme: "default",
    height: "auto",
    viewportMargin: Infinity,
    mode: {
      name: "javascript",
      json: true,
      statementIndent: 2
    },
    lineNumbers: true,
    lineWrapping: true,
    indentWithTabs: false,
    tabSize: 2
  };

  return (
    <div className="panel panel-default">
      <div className="panel-heading">Schema Editor</div>
      <CodeMirror
        value={codeEditorState}
        options={cmOptions}
        autoCursor={false}
        onChange={(editor, data, value) => onChange(value)}
      />
    </div>
  );
};

export default CodeEditorContainer;

Edit: The issue was the way i was parsing the JSON to a string instead of

JSON.stringify(json)

I used

JSON.stringify(json, null, 2)


Solution

  • The issue was the way i was parsing the JSON to a string instead of

    JSON.stringify(json)

    I used

    JSON.stringify(json, null, 2)