react-server-example
A simple (no compile) example of how to do server-side rendering with the React library so that component code can be shared between server and browser, as well as getting fast initial page loads and search-engine-friendly pages.
A more complex example with shared routing and data fetching can be found at react-server-routing-example.
Example
$ npm install$ node server.js
Then navigate to http://localhost:3000 and click on the button to see some reactive events in action.
Try viewing the page source to ensure the HTML being sent from the server is already rendered (with checksums to determine whether client-side rendering is necessary)
Here are the files involved:
App.js
:
var createReactClass = var DOM = var div = DOMdiv button = DOMbutton ul = DOMul li = DOMli // This is just a simple example of a component that can be rendered on both// the server and browser moduleexports =
browser.js
:
var React = var ReactDOM = // This is our React component, shared by server and browser thanks to browserifyvar App = React // This script will run in the browser and will render our component using the// value from APP_PROPS that we generate inline in the page's html on the server.// If these props match what is used in the server render, React will see that// it doesn't need to generate any DOM and the page will load faster ReactDOM
server.js
:
var http = var browserify = var literalify = var React = var ReactDOMServer = var DOM = var body = DOMbody div = DOMdiv script = DOMscript// This is our React component, shared by server and browser thanks to browserifyvar App = React // A variable to store our JS, which we create when /bundle.js is first requestedvar BUNDLE = null // Just create a plain old HTTP server that responds to two endpoints ('/' and// '/bundle.js') This would obviously work similarly with any higher level// library (Express, etc)http // A utility function to safely escape JSON for embedding in a <script> tag { return JSON // Only necessary if interpreting as JS, which we do // Ditto}