Render React components on the server with PHP

Earlier today, I stumbled upon a tweet promoting Facebook's very own React rendering library, based on PHP's v8js, already more than a year and a half of age and surprisingly unpopular - although its poor architecture and flexibility may be a good start in a quest for reasons.

It indeed is designed to spit out, separately, the markup rendered from your root component, and the JavaScript code required to bootstrap the application clientside. The fact it writes the latter itself requires React to be declared in the global scope; however, the major PITA is the fact it needs to be fed React's source and your own separately. Both of these make it utterly incompatible with modern JS build tools and their use of module systems - in my case, native ES6 modules transpiled by Babelify.

I thus decided to bypass it and see how difficult it would be to mimic its behaviour, but in a much simpler way, by simply feeding V8js my bundled, plain-old-ES5 code, with its own bootstrap code using the module syntax - the clientside code, actually.

It turned out great! A quick hack on the entry point:

import React from 'react';
import MyComponent from './components/my';

if ('undefined' !== typeof document) {
React.render(<MyComponent />, document.body);
} else {
print(React.renderToString(<MyComponent />));
}

And you're good to go:

$v8js = new V8Js();
ob_start();
$v8js->executeString(file_get_contents('/path/to/app.js'));
$content = ob_get_clean();

echo($content); in the client page then displays your gorgeous React app, rendered on the server.

Have fun!