Search code examples
reactjssingle-page-applicationflux

How to load light-weight html at first load with ReactJS?


How can i make my webapp render server-side and send only ready-to-use html to the client, if the client didn't download main.js file yet?


Solution

  • On the server, use React.renderToString (https://facebook.github.io/react/docs/top-level-api.html#react.rendertostring) with the same component JSX and the same props. Then, in your server-rendered template, place the generated string of markup in the same container element where you mount your React component client-side.

    React components will generate the same markup in the browser and on the server given the same props. React in the browser is smart enough (via the value of the data-react-id attribute) to recognize that a component has been already rendered to a string on the server and delivered to the browser within the initial page load. So, it won't render it again—it will just hook up the component's events.

    If your HTTP server isn't Node-based, you can use a simple messaging implementation (e.g. ZeroMQ or Redis pub/sub) to send rendering requests to a tiny Node script running on the same server. This script should have filesystem access to the same JSX components that you use client-side. The Node script should accept the path to the component JSX and a props object, and return the output of React.renderToString to your main HTTP server for inclusion in a template.