M
M
Maxim2015-07-19 17:06:09
Node.js
Maxim, 2015-07-19 17:06:09

How to do server rendering with React?

Asked a question to make server rendering for application on react. Found examples, everything turned out. But what about the compiled application into one file? It turns out that the server gives 3 static files: bundle.js, bundle.js.map and index.html.
I will be grateful for advice.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
L
Lesha Fedoseev, 2015-07-19
Antonikhin @STJ

index.html - it shouldn't be there.
There must be a template (jade, handlebars, whatever) into which:
The server renders this template and sends the html with the client application to the client.
If this is a SPA:

import express    from 'express';
import React      from 'react';
import Router     from 'react-router';
import Location   from 'react-router/lib/Location';

import App        from '/path/to/App';
import routes     from '/path/to/routes';


const app = express();

app.use(express.static(path.join(__dirname, 'public')));

app.use('/', middleware);

function middleware(req, res, next) {
  
  const location = new Location(req.path, req.query);
  
  Router.run(routes, location, (error, initialState, transition) => {
    
    const body   = React.renderToString(<App {...initialState} />);
    const layout = `${process.cwd()}/path/to/layout.jade`;
    const html   = Jade.compileFile(layout, { pretty: false })({ body });
    
    res.send(html);
    
  });
  
}

If it's static:
import express  from 'express';
import React    from 'react';

import Main     from 'components/Main';
import About    from 'components/About';


const app = express();

app.use(express.static(path.join(__dirname, 'public')));

app.get('/', (req, res) => middleware(req, res, Main));
app.get('/about', (req, res) => middleware(req, res, About));

function middleware(req, res, Component) {
  
  const body   = React.renderToString(<Component />);
  const layout = `${process.cwd()}/path/to/layout.jade`;
  const html   = Jade.compileFile(layout, { pretty: false })({ body });
  
  res.send(html);

}

/* Jade Layout */

doctype html
html
  
  head
    // head stuff...

  body
    #app!= body
    script(src="/bundle.js")

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question