lundi 12 janvier 2015

react.js - Server-side rendering and routes strategies


I'm currently starting my first React app with server-side rendering. The problem is that I want to choose the most solid strategy.


What I'm currently trying to do:




  • using Swig as template engine for Express app and inserting stringified React component like 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 into components on both server-side 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 renders on server perfectly, but client doesn't know that I have name prop..


client



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

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


Which throws me a warning from React and rerenders the page without name.




Another question here is routing.. I assume that it's better to render app on server when some route is requested but then I will prefer to have client-side location change when user goes through application..


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




So what is the best strategy from your experience to render React components on the server?





Aucun commentaire:

Enregistrer un commentaire