Render React Components from PHP

折月煮酒 提交于 2019-12-03 20:08:49

You can look at https://github.com/reactjs/react-php-v8js

It renders react UI components on the server-side with PHP.

The implementation is very simple and the only requirement is that you need to be able to setup the V8Js PHP extension on your server.

The short answer is: not really.

The only sensible way to do it would be having a node process running which php can request renders from. This isn't a bad solution especially for pages that are heavily cached.

I suggest setting it up in a very dynamic way:

<?php 
function render_component_to_string($component, $data) 
{
  $url = "http://localhost:9000/components/" 
    . $component 
    . "?data=" 
    . rawurlencode(json_encode($data));
  return file_get_contents($url)
}
?>
<div id="myFilteredList">
  <?= render_component_to_string("FilteredList", 
        array("items" => items, "title" => "My List")) ?>
</div>

In node.js:

var app = require('express')(); // express@4.x
var React = require('react');

// create a dictionary of components 
// Object.create(null) because the key is supplied
var components = Object.create(null);
components.FilteredList = require('./components/filtered-list.js');

app.get('/component/:componentName', function(req, res){
  var component = components[req.params.componentName];

  // safety first!
  if (!component) {
    console.error("Invalid component", req.params.componentName);
    return res.send(404);
  }

  // more safety
  try {
    var data = JSON.parse(req.query.data);
  }
  catch (e) {
    console.error("Invalid JSON", req.params.componentName, req.query.data);
    return res.send(400);
  }

  // render and send the result back
  try {
    var result = React.renderComponentToString(component(data));
  }
  catch (e) {
    console.error('Could not render', req.params.componentName,
                  'with props', data);
    console.error(e.message, '\n', e.stack);
    return res.send(400);
  }
  res.send(result);
});


app.listen(9000);

This of course assumes your components are in commonjs modules. If they're not, this is another reason to do so!


I haven't used php in a few years, so please update this answer if I made any mistakes.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!