Colorfield logo

Drupalicious

Published on

Drupal 8 progressive decoupling with React

Authors
React logo

Progressive decoupling and ES6 support on Drupal 8 are definitely gaining some momentum.
After having tested several methods to make use of React within Drupal, I had a look a the React Comments module. What I like about the approach that the maintainers took, is that React is:

  • Drupal environment agnostic, self contained
  • standard: relies on the well spread create-react-app
  • developer friendly: the theme can use libraries override and the bundling process is really easy.

Over all, I found there something simple to get started with and to maintain.

It may not be a good fit for sharing React among several modules, but it is ok for building a single app embedded in a Drupal website.

The React Comments method has been derived in this repository to have a kind of boilerplate to run tests on.
It also provides a demo that loads article nodes from a JSON API endpoint.

The development process is really straightforward:

React
  1. cd in /path/to/module/react_app/js/src.
  2. Install dependencies with yarn install.
  3. Copy the constants/.env.example.js file to constants/.env.local.js and set there your Drupal 8 site url. It will be used while debugging React as a standalone app for JSON API requests.
  4. Edit App.js and your components.
  5. Run yarn start to start the React development server and test your app outside of Drupal.
  6. Run php build.php to bundle the dist js and css that are referenced by react_app.libraries.yml.
Drupal

Generate some articles. Install devel_generate, then:

drush genc 20 --types=article

Install JSON API

composer require drupal/jsonapi
drush en jsonapi

Head to http://drupal8site/react-app/app to access the embedded React app, it should show up a list of articles loaded via React.

Resources