Search code examples
reactjscodemirrorreact-codemirror

React get codemirror value onClick


I am trying to get the following code below to display the CodeMirror onChange value when the button is clicked and then display that value inside the "output" div.

I am fairly new to react so not sure if it's best to pass the value through state or if there's an easier method.

Here is my code so far:

import React, { Component } from "react";
import { UnControlled as CodeMirror } from "react-codemirror2";
import "codemirror/mode/javascript/javascript";
import "codemirror/lib/codemirror.css";

export default class Code extends Component {
  render() {
    return (
      <div>
        <CodeMirror
          value='console.log("Hello World")'
          options={{
            mode: "javascript",
            lineNumbers: true
          }}
          onChange={(editor, data, value) => {
            console.log(value);
          }}
        />
        <button onClick={}>run code</button>

        <div className="Output">
          <p>// Value should go here</p>
        </div>
      </div>
    );
  }
}

Solution

  • You can make use of state to maintain your values, and show output from your state,

    class Code extends Component {
      constructor(props) {
        super(props)
        this.state = {
          runCode: false,
          outputText: 'console.log("Hello World")',
        }
      }
      runCode = () => {
        this.setState({runCode: true})
      }
      render() {
        return (
          <div>
            <CodeMirror
              value={this.state.outputText}
              options={{
                mode: 'javascript',
                lineNumbers: true,
              }}
              onChange={(editor, data, value) => {
                this.setState({
                  runCode: false,
                  outputText: value,
                })
              }}
            />
            <button onClick={this.runCode}>run code</button>
    
            <div className="Output">
              <pre>{this.state.runCode && this.state.outputText}</pre>
            </div>
          </div>
        )
      }
    }
    

    Demo - Output appended on click of button.

    Demo1 - Outout appended as you type in.