Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
Download
80743 views
1
<?php
2
3
// Prevent this from handling anything that isn't index.php.
4
if ($_SERVER["REQUEST_URI"] !== "/" && $_SERVER["REQUEST_URI"] !== "/index.php") {
5
return false;
6
}
7
8
// URL to the box running `node server.js`
9
define('RENDER_SERVER', 'http://localhost:3000/');
10
11
function react_component($module, $props) {
12
$props_json = json_encode($props);
13
14
// Try to server-render the component if the service is available.
15
// If it isn't, no big deal: the client will transparently render
16
// the markup!
17
$server_markup = @file_get_contents(
18
RENDER_SERVER .
19
'?module=' .
20
urlencode($module) .
21
'&props=' .
22
urlencode($props_json)
23
);
24
25
$container_id = uniqid();
26
$container_id_for_js = json_encode($container_id);
27
$module_for_js = json_encode($module);
28
29
// Generate the code required to run the component on the client.
30
// We assume that the Browserify bundle is loaded in the page already
31
// and that you used -r to get a global require() function that provides
32
// every $module you may request as well as React.
33
// Note that this solution is simple but I don't think it scales to
34
// multiple large pages very well. For that you'd be better off using
35
// webpack.
36
$startup_code = <<<SCRIPT
37
<script>
38
(function() {
39
var React = require('react');
40
var Component = require($module_for_js);
41
React.render(
42
React.createElement(Component, $props_json),
43
document.getElementById($container_id_for_js)
44
);
45
})();
46
</script>
47
SCRIPT;
48
49
$container_markup = '<div id="' . $container_id . '">' . $server_markup . '</div>';
50
51
return $container_markup . $startup_code;
52
}
53
?>
54
55
<html>
56
<head>
57
<title>React server rendering example</title>
58
<script src="static/bundle.js"></script>
59
</head>
60
<body>
61
Welcome to the React server rendering example. Here is a server-rendered React component:
62
<?php echo react_component('./src/App', array('name' => 'Pete')); ?>
63
</body>
64
</html>
65
66