Skip to content

Instantly share code, notes, and snippets.

@austinlyons
Last active January 27, 2016 03:55
Show Gist options
  • Save austinlyons/a7e50b00162677984f5a to your computer and use it in GitHub Desktop.
Save austinlyons/a7e50b00162677984f5a to your computer and use it in GitHub Desktop.
Universal React in Node
'use strict';
const React = require('react');
const ReactDOMServer = require('react-dom/server');
const ReactApp = require("./es5-lib/ReactApp");
const express = require('express');
const app = express();
app.use('/static', express.static('public'));
app.get('/', (req, res) => {
// instantiate the React component
const rApp = React.createFactory(ReactApp)({});
// write out the component to HTML string
const reactHtml = ReactDOMServer.renderToString(rApp);
// create final HTML to ship using string templating
// by injecting the react HTML into this string
const html = `
<!DOCTYPE html>
<html>
<head>
<title>JSON Formatter</title>
</head>
<body>
<div id="app">${reactHtml}</div>
<script src="/static/js/react-app.js"></script>
</body>
</html>
`;
// send to the browser
res.send(html);
});
const server = app.listen(9000, () => {
let port = server.address().port;
console.log(`Server running at http://localhost:${port}`);
});
@michelmattos
Copy link

For this to work with Babel 6, you need to change the line 5:

const ReactApp = require("./es5-lib/ReactApp");

To:

const ReactApp = require("./es5-lib/ReactApp").default;

Or you will get the error Invariant Violation: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object.

This happens because you're using export default in your ReactApp.jsx

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment