Adding React to Backdrop CMS: A guide for a progressively decoupled application.

Just because Backdrop CMS is a fork of Drupal doesn’t mean everything is the same. Fortunately adding React to a page is a fairly straight forward endeavor. You can walk through this project’s source code on GitHub.

Module Creation

There are only a few requirements to build a module for Backdrop. Inside our module’s project folder we need to make two files: a .info and a .module file

Our first two files will be backdrop_sample_react_module.info and backdrop_sample_react_module.module.

backdrop_sample_react_module.info

name = Sample React App
description = This module serves as an example of a progressively decoupled React app.
backdrop = 1.x

backdrop_sample_react_module.module

<?php

    /** Implements hook_permission().
     *  Defines permissions for your application.
     */
    function backdrop_sample_react_module_permission() {
        $permissions = array(
            'administer sample react app' => array(
                'title' => t('Administer sample React app.')),
            'sample react app user' => array(
                'title' => t('Authenticated user functions'),
            ),
        );
        return $permissions;
    }

    /**
     * Implements hook_menu().
     * AKA: Routes
     * Define your application's routes using hook_menu.
     * Define Application endpoints: POST, GET available.
     * Return JSON with: 'delivery callback' =>
'backdrop_json_output',
     */
    function backdrop_sample_react_module_menu() {
        $items['sample-react-app'] = array(
            'access arguments' => array('sample react app user'),
            'description' => t('Sample application built in React for Backdrop CMS.'),
            'page callback' => 'sample_react_application_main_controller',
            'title' => t('Sample React Application'),
        );

        $items['sample-react-admin'] = array(
            'access arguments' => 'administer sample react app',
            'description' => t('Sample administration page.'),
            'page callback' => 'sample_react_application_admin_controller',
            'title' => t('Sample Admin Page'),
        );

        $items['sample-react-shared'] = array(
            'access arguments' => 'access content',
            'description' => t('Sample administration page.'),
            'page callback' => 'sample_react_application_shared_controller',
            'title' => t('Sample Shared Page'),
        );

        return $items;
    }

    /**
     * Application API Controllers
     */

    function sample_react_application_main_controller() {
        // Page visible only to authenticated users
        $page = "<h1>Hello Html</h1>";
        return $page;
    }

    function sample_react_application_admin_controller() {
        // Page visible only to admin users
        $page = "<h1>Hello Admin</h1>";
        return $page;
    }

    function sample_react_application_shared_controller() {
        // Page with shared authenticated and unauthenticated user experience.
        $page = "<h1>Hello HTML</h1>";
       return $page;
    }

A couple things to note about our module so far is that. Our .module file has an opening PHP tag but no matching closing tag. This is intentional.

So far — we’re only doing three things with our module. First, we use hook_permission() to define the various access permissions for our content. Then we use hook_menu() to define our application’s routes. hook_menu() will output an array where the keys are our routes and the values are the properties associated with those routes.

We’re able to restrict access to any of our routes by including the ‘access arguments’ key set to a value either defined in hook_permissions() or given by Backdrop. To allow a route to be accessible to unauthenticated users — use the permission ‘access content’ as our route sample-react-shared does above.

Finally, we define our controllers. These functions are called when our authenticated users visits the routes we set up in hook_menu().

Backdrop allows for several ways to output code to the client. Right now our controllers are outputting a vanilla string of HTML — shortly we’ll be using Backdrop’s render arrays to take advantage of some handy built-in functionality.

Test out your handiwork by enabling the module at admin/modules/list then visit the routes we made: /sample-react-app, /sample-react-admin, and /sample-react-shared.

Building the React App

While create-react-app is convenient, it isn’t the best way to build an app that is ready to be embedded into Backdrop. Fortunately setting up React from scratch isn’t terribly difficult.

Installing the Dependencies

Inside our module folder we’ll make a couple new folders that will house our app.

Lets put our app in:
backdrop_sample_react_module/js/react/sampleapp

Inside the terminal, navigate to the sampleapp folder and type: npm init

This will build out a basic package.json file that lists our application dependencies and scripts.

React needs a toolchain to build and render your code. We’ll start by installing the development dependencies.

npm install --save-dev @babel/cli @babel/core @babel/preset-env @babel/preset-react babel-loader webpack webpack-cli

After NPM installs the required dev dependencies we can install React.

npm install react react-dom

Add Webpack Config File

The webpack config file contains the settings that tell webpack how to handle and compile JSX.

Place this code below in a file named webpack.config.js

const path = require('path');
 
const config = {
 entry: './src/index.js',
 devtool: (process.env.NODE_ENV === 'production') ? false : 'inline-source-map',
 mode: (process.env.NODE_ENV === 'production') ? 'production' : 'development',
 output: {
   path: path.resolve(__dirname, 'build'),
   filename: 'app.bundle.js'
 },
 module: {
   rules: [
     {
       test: /\.js$/,
       exclude: /(node_modules)/,
       use: {
         loader: 'babel-loader'
       }
     }
   ]
 },
};
 
module.exports = config;

Edit package.json

We need to add a few items to our package.json file in order to be able to build our app.

 "scripts": {
   "build": "NODE_ENV=production webpack",
   "watch": "webpack --watch --progress"
 },

Add the build and watch scripts to your package.json scripts key.

Configure Babel

We’ll need to add a babel key to our package.json file to tell Babel how to handle our application.

 "babel": {
   "presets": [
     [
       "@babel/preset-env",
       {
         "targets": {
           "browsers": [
             "IE >= 11",
             "last 3 versions"
           ]
         }
       }
     ],
     "@babel/preset-react"
   ]
 }

Build Your App

Create a folder named src and add a file name index.js. This is the file that our toolchain will start the build process from.

import React from 'react';
import { render } from 'react-dom';

const App = () => {
    return (
        <div>Hello React</div>
    )
}

render(<App />, document.querySelector('#myapp'));

You should be able to run npm run watch to compile your app using development settings. Webpack will automatically watch your app’s files and recompile when they’re changed. When ready to deploy however it’s best to run npm run build to properly minimize the app for production.

Once built, you’ll see a new folder named build. Inside it will contain your app.bundle.js that we will include in our Backdrop module.

Include Your App in Backdrop

Back in our .module file we will need to change the output of our controller from HTML to a render array.

    function sample_react_application_main_controller() {
        // Page visible only to authenticated users
        $module_path = backdrop_get_path('module','backdrop_sample_react_module');
        $js_path = $module_path . '/js/react/sampleapp/build/app.bundle.js';
        $css_path = $module_path . '/css/styles.css';
        $page = array();
        $page['content'] = array(
            '#type' => 'markup',
            '#markup' => '<div id="myapp">Hello Html</div>',
            '#attached' => array(
                'js' => array(
                    array(
                        'data' => $js_path,
                        'every_page' => FALSE,
                        'group' => JS_THEME,
                        'type' => 'file',
                        'preprocess' => FALSE,
                        'scope' => 'footer',
                    )
                ),
                'css' => array(
                    array(
                        'data' => $css_path,
                        'every_page' => FALSE,
                        'group' => CSS_THEME,
                        'type' => 'file',
                        'preprocess' => FALSE,
                        )
                    ),
                ),
            );
        return $page;
    }

Instead of outputting HTML we’ve refactored our controller to output a backdrop render array. Importantly, we need to specify our scope as ‘footer’ in order to have our JavaScript load after the DOM elements have been loaded.

Conclusion

We’ve walked through the basic process to add React components to Backdrop CMS using progressive decoupling. This approach allows you to integrate your app without losing any of the features that make using a content management system so appealing. We don’t have to go fully headless just to use React.

Leave a Reply