Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to export Component for server side rendering in React

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

like image 775
Kuan Avatar asked Jan 12 '16 18:01

Kuan


People also ask

Which React tool is used for server-side rendering?

Next. js is used for server side rendering of react application . React along with other framework like angular and vue. js are traditional client side framework ,they run in browser but there are technology to run this framework on server side, and next.

Which class in React allows you to render your components on the server?

Introduction. Server-side rendering (SSR) is a popular technique for rendering a client-side single page application (SPA) on the server and then sending a fully rendered page to the client. This allows for dynamic components to be served as static HTML markup.


1 Answers

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 />);
like image 70
Jim O'Brien Avatar answered Sep 29 '22 01:09

Jim O'Brien