How Can I Make Add Firepad To My Reactjs Project?

- 1 answer

So I've been learning react, and wanted to make a basic firepad instance. My current setup is having one container div in my index.html, and having all of my react components rendering through that div. My current attempts and the code I'm showing with this have been in an environment with gulp and browserify, but I'm also playing around with ES6 and webpack. So I'm pretty flexible about getting this working as I learn. Here's the code:

"use strict"

var React = require('react')
  , Firebase = require('firebase')
  , fbRoot = 'myURL'
  , CodeMirror = require('codemirror')
  , Firepad = require('firepad')
  , firepadRef = new Firebase(fbRoot + 'session/')
  , myCodeMirror = CodeMirror(document.getElementById('firepad'), {lineWrapping: true})
  , myFirePad = Firepad.fromCodeMirror(firepadRef, myCodeMirror, { richTextShortcuts: true, richTextToolbar: true, defaultText: 'Hello, World!'});

var WritePage = React.createClass({
  render: function(){
    return (
        <div id="firepad"></div>

module.exports = WritePage;

The first error I was getting was that it couldn't find the codemirror.js file. Although CodeMirror was being correctly defined in Chrome's dev tools, I moved that from requiring the npm package to just linking the 2 needed codemirror files to my html. It then gave me an error about not being able to take .replaceChild of undefined. I then tried moving all of the dependency files over to my index.html, but still had the same .replaceChild error. Anyone have any experience with react and firepad? I read in the reactfire docs that it's one way binding from firebase to my site, which for my case making a read-only firepad would be fine. Like I said, I'm flexible all of this stuff is new to me.



From the link that Michael provided.

The problem is that you are trying to reference a DOM element before React has rendered your component.

, myCodeMirror = CodeMirror(document.getElementById('firepad'),{lineWrapping: true})
, myFirePad = Firepad.fromCodeMirror(firepadRef, myCodeMirror, {richTextShortcuts: true, richTextToolbar: true, defaultText: 'Hello, World!'});

By moving this code into componentDidMount(), it runs after the CodeMirror DOM element has been constructed and you'll be able to reference the DOM node. You will also probably find it easier to use the React ref attribute instead of document.getElementById().