11

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

2 Answers 2

8

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 />);
Sign up to request clarification or add additional context in comments.

2 Comments

thanks for reply. When I back to FB API, I realize it need to be a JSX style element too.
You can also do something like: reactDOM.renderToString(react.createFactory(componentFile)(), {}); And it should work when your component lives in a separate jsx file
2

Using a factory allows you to have all your components in separate files and instantiate them without using jsx syntax in your server. Very useful for the main wrapper component.

require('babel-core/register')({
  presets: ['react']
});

var express = require('express');
var reactDOM = require('react-dom/server');
var react = require('react');
var app = express();

app.get('/', function (req, res) {
  var mainFile = require('./app.jsx');
  var output = reactDOM.renderToString(react.createFactory(mainFile)({
    data: yourInitialData
  }));
  res.send(output);
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.