7

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)

chinds
  • 1,761
  • 4
  • 28
  • 54
  • Hi, Do you know why `CodeMirror` displays all `JSON` elements in single color? Its not highlighting everything correctly right? Just as in your case, Even in my case `application/lg+json` is displayed in `red font` and brackets in `black font` apart from that nothing is being highlighted correctly. Any idea how to fix this? – BATMAN_2008 Oct 15 '21 at 12:30
  • Hi, I stopped working on this project a long time ago, however this may help you https://stackoverflow.com/a/33495405/2274900 – chinds Oct 19 '21 at 16:11

1 Answers1

14

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)

chinds
  • 1,761
  • 4
  • 28
  • 54