Behavior of ReactDOM.render in componentDidMount method Ask Question

I’m struggling with a functionality of my code when using the render() method from ReactDOM in the componentDidMount() function from the React lifecycle.

I’m using react-codemirror to have a wrapper of the CodeMirror library that adapts good with React and I’m trying to add some default “Bookmarks” when the component has been mounted.

That part of my code looks like this:

componentDidMount() {
  var domContainer = document.createElement('span');
  var bookmarkElement = (<span>Test Bookmark</span>);

  this._codeMirror = this.reactCodeMirrror.getCodeMirror();
  this._codeMirror.replaceRange(' ', { line: 0, ch: 0 });
  this._codeMirror.markText({ line: 0, ch: 0 }, { line: 0, ch: 1 }, {
    replacedWith: ReactDOM.render(bookmarkElement, domContainer),
  });
}

I extracted the ReactDOM.render() method to a variable to check its value and was null. But for some reason, when I wrap the markText code inside a setTimeout() of a millisecond it renders the element correctly.

componentDidMount() {
  var domContainer = document.createElement('span');
  var bookmarkElement = (<span>Test Bookmark</span>);

  this._codeMirror = this.reactCodeMirrror.getCodeMirror();
  this._codeMirror.replaceRange(' ', { line: 0, ch: 0 });

  setTimeout(function () {
    this._codeMirror.markText({ line: 0, ch: 0 }, { line: 0, ch: 1 }, {
      replacedWith: ReactDOM.render(bookmarkElement, domContainer),
    });
  }, 1);
}

Edit: Adding a bit more information about the problem.

At this moment I have the following code in the render() method.

render() {
    <CodeMirror ref={(codeMirror) => { this.reactCodeMirror = codeMirror; }} />
}

That method is working OK, as the editor is being rendered, but I’m not able to dynamically add the “Bookmark” that is in the componentDidMount() method, as the ReactDOM.render() method is returning null when is not inside the setTimeout() method.


Is there anything I’m doing wrong or overlooking when using the ReactDOM.render() method? Is there any way to make it work correctly without the setTimeout() wrapper?

Thanks!

One thought on “Behavior of ReactDOM.render in componentDidMount method Ask Question”

Leave a Reply

Your email address will not be published. Required fields are marked *