Ad

How To Export Component For Server Side Rendering In React

- 1 answer

All:

I am pretty new to React, right now I am trying how to do server side rendering, I use Express.js as my server, so the code is like:

//server.js
var express = require("express");

var ReactDOMServer = require("react-dom/server");
var MyCom = require("./components"); 
var domstring = ReactDOMServer.renderToString(MyCom);

var app = express();
app.get("/", function(req, res){
    res.json({
        name: "new com",
        dom: domstring
    });
});

And

// components.js
var React = require("react");

var MyCom = React.createClass({
    render: function(){
        return (<h1>Hello, server side react</h1>);
    }
});

module.exports = MyCom;

I use babel to transpile the JSX, but when I start server, I do not know why I keep getting error like:

Invariant Violation: renderToString(): You must pass a valid ReactElement.

Could anyone give some clue why this not work?

Thanks

Ad

Answer

Your module exports a ReactComponent, and renderToString accepts a ReactElement (i.e. an instantiated ReactComponent).

In order to render it, you want to instantiate it like so:

ReactDOMServer.renderToString(<MyCom />);
Ad
source: stackoverflow.com
Ad