Home > database >  How to enable syntax validation in react-codemirror editor for javascript language in nextjs
How to enable syntax validation in react-codemirror editor for javascript language in nextjs

Time:10-12

I am using react-codemirror2 Editor in my Next.js application. The editor by default marks the syntax validation errors and warnings. I want to make sure when the user saves the code there is no syntax error in the code. I need to access the validation result, I don't know how to achieve that. here is my code:

import React, { Fragment } from "react";
let CodeMirror;
export default class Editor extends React.Component {
  state = {
    render: false,
    code: "",
  };
  componentDidMount = () => {
    CodeMirror = require("react-codemirror2");
    require("codemirror/lib/codemirror.css");
    require("codemirror/theme/eclipse.css");
    require("codemirror/addon/lint/lint.css");
    require("codemirror/addon/hint/show-hint.css");
    require("codemirror/mode/javascript/javascript.js");
    require("codemirror/addon/lint/javascript-lint");
    require("codemirror/addon/lint/lint.js");
    require("codemirror/addon/hint/javascript-hint");
    const { JSHINT } = require("jshint");
    window.JSHINT = JSHINT;
    this.setState({ render: true });
  };
  SaveCode() {
    // here I need to validate the [this.state.code]
    // if there is no syntax error then save it
  }
  render() {
    if (!this.state.render) return null;
    const { UnControlled } = CodeMirror;
    return (
      <>
        <UnControlled
          value={this.state.code}
          onBeforeChange={(a, b, value) => {
            this.setState({ code:value });
          }}
          options={{
            readOnly: false,
            mode: "javascript",
            theme: "eclipse",
            lineNumbers: true,
            lint: true,
          }}
        />
        <div style={{ padding: "10px 25px 25px", textAlign: "right" }}>
          <button onClick={this.SaveCode}>Save</button>
        </div>
      </>
    );
  }
}

CodePudding user response:

You can use the onUpdateLinting function to receive linting errors. Change the lint field in the options prop of your CodeMirror component like so:

lint: {
  onUpdateLinting: this.handleErrors,
},
  • Related