Forest header image

Symfony Finland
Random things on PHP, Symfony and web development

Introduction to React.js Components and Server Side Rendering in PHP

React is an interface library that is rapidly gaining ground. It can be considered as similar to what Angular and Ember, for example, are. As opposed to Angular and Ember React.js focuses on User Interfaces alone, being neutral on routing and other duties. React can also be rendered on the server side, which is not unique - but very natural to it.

Most developers choose to write React components in a JavaScript dialect known as JSX. It is essentially a mix of HTML and JavaScript. The tags need to be closed and there are some differences like using the attribute className instead of just class for defining CSS classes. JSX is transformed into JavaScript for manipulating the DOM.

For example JSX:

var HelloMessage = React.createClass({
  render: function() {
    return <div>Hello {this.props.name}</div>;
  }
});
ReactDOM.render(<HelloMessage name="John" />, mountNode);

is transformed to JavaScript by a JSX parser:

"use strict";
var HelloMessage = React.createClass({
  displayName: "HelloMessage",
  render: function render() {
    return React.createElement(
      "div",
      null,
      "Hello ",
      this.props.name
    );
  }
});
ReactDOM.render(React.createElement(
HelloMessage, { name: "John" }
), mountNode);

This is then rendered to DOM structure by the React library itself, with the end result being a simple:

<div>Hello John</div>

This process of turning JSX to HTML can take place either on the server or in the browser. Life was simpler when a <div>Hello <?=$name; ?></div> sufficed as a first.

Server side component rendering

The above example is a simple example that could be done with a number of different technologies in better ways with simpler technologies. Embedding components within components and binding them together with state management is a very powerful tool. Once your application grows in complexity you can start seeing returns.

React.js popularised the concept of isomorphic rendering. This is a fancy set of words for rendering the exact same UI components both on the server and on the client, leading to less code duplication. The de-facto rendering backend is Node.js - a server side platform that executes JavaScript using the V8 Engine or Chakra in Windows IoT.

Server side rendering of components is convenient as it renders the first view on the server to allow a faster initial experience for the users - rather than rendering it completely on the client. React can hook up to this pre-built state, allowing for a fluent single page app, no-page-loads experience form the first load onwards.

Learn more about engineering software React, Flux and other accompanying software: A Comprehensive Guide to Test-First Development with Redux, React, and Immutable

Rendering React Components in PHP or Twig

PHP could technically be used to render React components in native PHP. Since the community would need to maintain compatibility and feature parity with JSX and React itself, it is not feasible. This takes us into the ways that we can render React components in PHP:

  • Use the V8Js extension to run an embedded V8 engine
  • Execute node.js processes on demand
  • Run a node.js rendering daemon for rendering

Embedded rendering is supported by the Facebook team in the form of an experimental library that executes React using the V8Js extension. It gives a native-feeling API for PHP developers as well as good performance and little overhead. The downside is that installing the extension is not trivial (due to version compatibility issues) and not widely available out-of-the-box by popular Linux distributions.

Executing node.js processes on demand with the Symfony Process Component or some other method is easy to deploy, but is suboptimal in terms of resource usage. Scaling and reliability of this crude method are other downsides. An example implementation is described in the Twig rendering POC article on this site.

Running a continuous Node.js process waiting for requests to come in is a feasible option. It defers the responsibility completely to an external component. All communications would take place in HTTP, much like with integrations of popular search engines powered by Lucene. The daemon could be packaged with the PHP application and allows scaling by moving to a separate server or servers.

React.js and PHP are not worlds apart

At the time of writing there is no de-facto way of rendering React components using PHP and all of the above are subject to continuous change. Node.js will power a large percentage of React powered applications, but bridging PHP and the React component ecosystem using Node.js is a valid concept.

Facebook itself has moved on from PHP to their own derivative of it, known as Hack. As both Hack and React.js originate from Facebook, they are also merging them together with a technology known as XHP which is also available as a PHP extension and might very well become popular.

Consider this following Hack snippet and as a PHP developer you'll likely experience something similar to JSX Shock:

<?hh
$list = <ul />;
foreach ($items as $item) {
  $list->appendChild(<li>{$item}</li>);
}

Facebook has a growing library of react component and they sometimes they want to use those on a static page without rewriting the whole section with React, but duplicating rendering in XHP and React can be lead to long-term pain. XHP-JS is a thin XHP wrapper around React elements as described in the article on building efficient user interface components with Hack, React, and XHP.

As the line between back end and front end development continues to blur, syntax such as this one might become more common in the years to come. Separating markup and logic is no longer once again not blasphemy, but convenient.

React can be like inline PHP

What is worth about JSX is that fluently switches in and out of JavaScript and HTML Markup. You could think of it a bit like classical PHP where tags were opened and closed amidst of templating; enabling programming logic and even SQL queries right within the template.

JSX and React were developed by Facebook for large teams, for which they do work well. But developers working on Facebook are likely to be better developers than the average Joe. As far as I can see React and accompanying technologies come with default no hard mechanism for enforcing application structure. This can lead to abuse of the concept and create a huge serving of asynchronous reactive spaghetti or whatever you want to call it.

I hope the React intoxicated masses will not start implementing everything with it, just because WordPress Calypso and all. Sometimes a few lines of jQuery can be better for the bottom line on the short term and mental health in the long run. In other cases React is worth the investment.


Written by Jani Tarvainen on Sunday December 13, 2015
Permalink - Tags: react, php, node, javascript

« Migrating large sites to HTTP/2 - eZ Systems releases Content Management products built on the Symfony Framework »