JedWatson/react-codemirror

how can I beautify(formatting) code after load

Mostafasaffari opened this issue · 2 comments

Hi
how can I beautify code? like this

@Mostafasaffari check out react-codemirror2

I actually do this in the demo (code here)

Use react-codemirror2. Here how i solve this:

import React, { Component } from "react";
// import CodeMirror from "react-codemirror";
import { Controlled as CodeMirror } from "react-codemirror2";
require("codemirror/theme/dracula.css");
require("codemirror/mode/xml/xml");
require("codemirror/mode/markdown/markdown");
let hBeautify = require("js-beautify").html;

export class HtmlEditor extends Component {
  state = {
    code: "null",
  };
  updateCode = (e) => {
    this.setState({ code: e });
    console.log("object");
  };
  autoFormatSelection = () => {
    let code = this.state.code;
    // console.log(code);
    let formatedHTML = hBeautify(code, { indent_size: 2 });
    console.log(formatedHTML);
    this.setState({ code: formatedHTML });
  };
  render() {
    let options = {
      height: "150px",
      lineNumbers: true,
      tabSize: 2,
      mode: "xml",
      theme: "dracula",
      extraKeys: { "Shift-Tab": this.autoFormatSelection },
    };
    return (
      <div className="col-4 bg-light p-0">
        <div className="card text-white bg-dark rounded-0 h-100">
          <div className="card-header">
            HTML
            <a
              className="btn btn-outline-light float-right btn-sm"
              href="#"
              data-toggle="modal"
              data-target="#codeconfig"
            >
              <i className="fa fa-cog" />
            </a>
          </div>
          <div className="card-body p-0">
            <CodeMirror
              value={this.state.code}
              options={options}
              onBeforeChange={(editor, data, value) => {
                this.setState({ code: value });
              }}
              onChange={(editor, data, value) => {
                this.setState({ code: value });
                console.log("object");
              }}
            />
          </div>
        </div>
      </div>
    );
  }
}

export default HtmlEditor;