Reputation: 21314
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?
Upvotes: 3
Views: 4115
Reputation: 159135
To correctly "upgrade" a server-rendered component into a client-managed component (e.g. without the warning), you need to mount the same component on the client as you rendered on the server, and pass it the same props. If the props can be dynamic, then you'll also need to get the props from the server to the client, e.g. by serializing them to JSON and then reading them out on the client before the component mounts.
A good React routing solution (react-router is a great choice) will allow you to declaratively set up your routes based on the URL and query parameters, which frees you from having to manage and serialize that data yourself. Here's a quick example from the react-router docs.
Upvotes: 1