Search code examples
javascriptjquerycodemirrorreactjs

Reactjs - what is the workflow to force a refresh?


I'm just trying to create a react component wrapping the CodeMirror (4.1) editor.

I came across this problem for which there is a workround via forcing a refresh once the component has loaded, but I'm not quite sure of the workflow I need to achieve this when react is added into the picture.

The suggestion is that to overcome the error I would need to

"Call .refresh() after resizing the wrapping container."

My code is currently as follows in the Editor component:

  function ($, React, CodeMirror) {

    return React.createClass({

      render: function () {
        console.log("render-editarea");
        return (
          <textarea id="editarea">
-- Comment here
USE [All Data Items];
SELECT ID FROM [Test Event]
          </textarea>
        )
      },

      componentDidMount: function () { 
        var onExecute = this.props.onExecute;
        var editorNode = document.getElementById("editarea");
        console.log("componentDidUpdate-editarea:" + editorNode); 
        var editor = CodeMirror.fromTextArea(editorNode, {        
          lineNumbers: true,
          matchBrackets: true,
          indentUnit: 4,
          mode: "text/x-mssql",
          extraKeys: {"Ctrl-E": function(cm) {    
            console.log(editor.getValue());
            onExecute(editor.getValue());
          }}
        });
      },

and it is loaded via the Render function of the parent component

I have tried

  • hooking the window resize event (as shown in the React manual) in the editor component.
  • forcing a refresh in the parent component's componentDidMount function using $("#editarea").refresh();

but neither of these appeared to work

So I'd be grateful if someone could show me the right way to do it.

Many thx


Solution

  • Use the ref attribute to reference rendered nodes rather than IDs or DOM selectors:

    function ($, React, CodeMirror) {
    
      return React.createClass({
    
        render: function () {
          console.log("render-editarea");
          return (
            <textarea ref="editarea">
    -- Comment here
    USE [All Data Items];
    SELECT ID FROM [Test Event]
            </textarea>
          )
        },
    
        componentDidMount: function () { 
          var onExecute = this.props.onExecute;
          var editorNode = this.refs.editarea;
          console.log("componentDidUpdate-editarea:" + editorNode); 
          var editor = CodeMirror.fromTextArea(editorNode, {        
            lineNumbers: true,
            matchBrackets: true,
            indentUnit: 4,
            mode: "text/x-mssql",
            extraKeys: {"Ctrl-E": function(cm) {    
              console.log(editor.getValue());
              onExecute(editor.getValue());
            }}
          });
        },