Search code examples
node.jsreactjsisomorphic-javascript

React - server side component rendering


I'm trying to renderToString a very simple React component on the server:

/** @jsx dom */
var React = require("react");

var Title = React.createClass({
  render: function(){
    return(<h1>Hello World</h1>) 
  }
});

module.exports = React.createFactory(Title);

When I call ReactDOMServer.renderToString (Component) I'm getting Error: Invariant Violation: renderToString(): You must pass a valid ReactElement.

If I do React.createElement (Title) instead, I get

return(dom.h1(null, "Hello World")) 
           ^
ReferenceError: dom is not defined

Routes file:

var express = require('express'),
    router = express.Router(),
    React = require("react")
    ReactDOMServer = require("react-dom/server");  
    JSX = require('node-jsx').install({
      extension: '.jsx'
    }),
    AssessmentComponent = require("../react/components/title.react.jsx");

I have no idea why this isn't working!


Solution

  • So I was making a few mistakes. Solutions below:

    a) Using babel/register when requiring the component meant that transpiling can be done on the fly without any faff ;)

    b) dom was being inserted by Babel's @jsx dom syntax. No need for that now that babel/register is being used.

    c) Exporting the component with createFactory is not advised because other users of the component may want to call createElement on it.

    d) I called createFactory on the routes file, but it appears to return a function which needed to be called. - ReactDOMServer.renderToString(Component())