Last active
January 27, 2016 03:55
-
-
Save austinlyons/a7e50b00162677984f5a to your computer and use it in GitHub Desktop.
Universal React in Node
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'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}`); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
For this to work with Babel 6, you need to change the line 5:
To:
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