React.js - Server Side Rendering and Routing Strategies

I am currently running my first React app with server side rendering. The problem is, I want to choose the most solid strategy.

What I am currently trying to do:

  • using Swig as a templating engine for an Express app and injecting a string React component like a template variable:

    <!doctype html>
    <html lang="en">
      <head>
         <meta charset="utf-8">
         <title>Title</title>
      </head>
      <body>
         <div id="react-mount">{{reactHTML|safe}}</div>
         <script src="/build/bundle.js"></script>
      </body>
    </html>
    
          

  • here is the problem of passing props to components on both server and client side:

server

var Box = require('./src/components/Box.jsx');
function renderify (component, props) {
   var reactHTML = React.renderToString(React.createElement(component, props));
   return {reactHTML: reactHTML};
}

app.get('/', function (req, res) {
   res.render('layout', renderify(Box, {name: 'My Box'}));
});

      

This displays the server fine, but the client doesn't know I have a name

prop ..

customer

var React = require('react');
var Box = require('./components/Box.jsx');

React.render(<Box />, document.getElementById('react-mount'));

      

Which gives me a warning from React and rewrites the page without name

.


Another question here is routing. I guess it is better to display the application on the server when some route is requested, but then I would rather change the location on the client side when the user is going through the application.

Does this mean that routes must be duplicated on both the client and the server?


So what's the best strategy in your experience for rendering React components on the server?

+3


source to share


1 answer


To properly "update" a server-rendered component in a client-managed component (for example, without warning), you need to mount the same component on the client as on the server and pass the same props to it. If the props can be dynamic, you will also need to get the props from the server to the client, for example. by serializing them to JSON and then reading them on the client before mounting the components.



A good React routing solution ( react-router is a great choice) will allow you to declaratively configure routes based on URL and request parameters, which frees you from having to manage and serialize this data yourself. Below is a short example from the responder docs.

+1


source







All Articles