Kosmetika
Kosmetika

Reputation: 21314

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:

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?

Upvotes: 3

Views: 4115

Answers (1)

Michelle Tilley
Michelle Tilley

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

Related Questions