J
J
jspie2017-09-09 19:43:28
JavaScript
jspie, 2017-09-09 19:43:28

How can I make an SSR React app using express?

Good afternoon, I decided to find out how to make an SSR application, but I came to a dead end. I usually refer to index.html.

<!DOCTYPE html>
<html>
<head>
  <title>Todo</title>
  <meta name="viewport" content="width=device-width initial-scale=1">
  <link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">
  <link href="https://fonts.googleapis.com/css?family=PT+Sans+Narrow" rel="stylesheet">
</head>
<body>
<div id="root"></div>
<script type="text/javascript" src="app.bundle.js"></script>
</body>
</html>

On webpack set up main.js entry point
import React from 'react';
import {
  AppContainer
} from 'react-hot-loader';
import ReactDOM from 'react-dom';
import Component from './components/App';

ReactDOM.render(
  <AppContainer>
  <Component />
  </AppContainer>,
  document.getElementById('root')
)

if(module.hot){
  module.hot.accept(()=>{
   	ReactDOM.render(
    <AppContainer>
      <Component />
    </AppContainer>,
    document.getElementById('root')
  )
  })
}

Can you tell me how can I do it through express? There are examples, but they are all different and I can't figure out how to work with it. Maybe through hbs it can be done somehow?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
Ilya Gerasimov, 2017-09-11
@Omashu

More or less like this:

import React from 'react';
import { StaticRouter } from 'react-router'
import { Provider } from 'react-redux'
import ReactDOMServer from 'react-dom/server';

import Store from './store';

export default (Url, Component, Props = {}, Context = {}) => {
  return ReactDOMServer.renderToString(
    <Provider store={Store}>
      <StaticRouter
        location={Url}
        context={Context}>
        <Component {...Props}/>
      </StaticRouter>
    </Provider>
  );
}

import reactRenderToString from './reactRenderToString'
import Component from '../client/routes/Home.jsx';

console.log(reactRenderToString('/', Component))

At the Html output, a line marked up with react, insert it into #app using a template engine or whatever you have, the page, scripts are loaded, the react picks up the marked html and hangs the handlers. PS You should be careful with various libraries on the client, because a lot of shit code (including ours) does not allow the collector to collect garbage and each of our renders can lie in memory until it fails...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question