<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Programming &#8211; Jaytria</title>
	<atom:link href="https://api.jaytria.com/tag/programming/feed/" rel="self" type="application/rss+xml" />
	<link>https://api.jaytria.com</link>
	<description>Web &#124; Technology</description>
	<lastBuildDate>Sat, 06 Nov 2021 01:42:56 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.9.4</generator>

<image>
	<url>https://api.jaytria.com/wp-content/uploads/2019/06/cropped-Jaytria-1-32x32.png</url>
	<title>Programming &#8211; Jaytria</title>
	<link>https://api.jaytria.com</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>Adding React to Backdrop CMS: A guide for a progressively decoupled application.</title>
		<link>https://api.jaytria.com/2021/03/30/adding-react-to-backdrop-cms-a-guide-for-a-progressively-decoupled-application/</link>
					<comments>https://api.jaytria.com/2021/03/30/adding-react-to-backdrop-cms-a-guide-for-a-progressively-decoupled-application/#respond</comments>
		
		<dc:creator><![CDATA[Justin]]></dc:creator>
		<pubDate>Tue, 30 Mar 2021 23:11:30 +0000</pubDate>
				<category><![CDATA[Backdrop CMS]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[React]]></category>
		<category><![CDATA[Web Development]]></category>
		<guid isPermaLink="false">https://blog.jaytria.com/?p=170</guid>

					<description><![CDATA[Adding React to Backdrop CMS is easy enough once you understand how to do it.]]></description>
										<content:encoded><![CDATA[
<p class="has-drop-cap">Just because <a href="https://backdropcms.org">Backdrop CMS</a> is a fork of <a href="https://drupal.org">Drupal</a> doesn&#8217;t mean everything is the same. Fortunately adding React to a page is a fairly straight forward endeavor. You can walk through this project&#8217;s source code on <a href="https://github.com/jsitter/backdrop_sample_react_module">GitHub</a>.</p>



<h3 class="wp-block-heading">Module Creation</h3>



<p>There are only a few requirements to build a module for Backdrop. Inside our module&#8217;s project folder we need to make two files: a <strong>.info</strong> and a <strong>.module</strong> file</p>



<p>Our first two files will be <strong>backdrop_sample_react_module.info</strong> and <strong>backdrop_sample_react_module.module</strong>.</p>



<p><strong>backdrop_sample_react_module.info</strong></p>



<pre class="wp-block-code"><code>name = Sample React App
description = This module serves as an example of a progressively decoupled React app.
backdrop = 1.x</code></pre>



<p><strong>backdrop_sample_react_module.module</strong></p>



<pre class="wp-block-code"><code>&lt;?php

    /** Implements hook_permission().
     *  Defines permissions for your application.
     */
    function backdrop_sample_react_module_permission() {
        $permissions = array(
            'administer sample react app' =&gt; array(
                'title' =&gt; t('Administer sample React app.')),
            'sample react app user' =&gt; array(
                'title' =&gt; 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' =&gt;
'backdrop_json_output',
     */
    function backdrop_sample_react_module_menu() {
        $items&#91;'sample-react-app'] = array(
            'access arguments' =&gt; array('sample react app user'),
            'description' =&gt; t('Sample application built in React for Backdrop CMS.'),
            'page callback' =&gt; 'sample_react_application_main_controller',
            'title' =&gt; t('Sample React Application'),
        );

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

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

        return $items;
    }

    /**
     * Application API Controllers
     */

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

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

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



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



<p> So far &#8212; we&#8217;re only doing three things with our module. First, we use <code>hook_permission()</code> to define the various access permissions for our content. Then we use <code>hook_menu()</code> to define our application&#8217;s routes. <code>hook_menu()</code> will output an array where the <strong>keys</strong> are our routes and the <strong>values</strong> are the properties associated with those routes.</p>



<p>We&#8217;re able to restrict access to any of our routes by including the <strong>&#8216;access arguments&#8217;</strong> key set to a value either defined in hook_permissions() or given by Backdrop. To allow a route to be accessible to unauthenticated users &#8212; use the permission <strong>&#8216;access content&#8217;</strong> as our route <strong>sample-react-shared</strong> does above.</p>



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



<p>Backdrop allows for several ways to output code to the client. Right now our controllers are outputting a vanilla string of HTML &#8212; shortly we&#8217;ll be using Backdrop&#8217;s render arrays to take advantage of some handy built-in functionality.</p>



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



<h3 class="wp-block-heading">Building the React App</h3>



<p>While <strong>create-react-app</strong> is convenient, it isn&#8217;t the best way to build an app that is ready to be embedded into Backdrop. Fortunately setting up React from scratch isn&#8217;t terribly difficult.</p>



<h3 class="wp-block-heading">Installing the Dependencies</h3>



<p>Inside our module folder we&#8217;ll make a couple new folders that will house our app.</p>



<p>Lets put our app in:<br><code>backdrop_sample_react_module/js/react/sampleapp</code></p>



<p>Inside the terminal, navigate to the <code>sampleapp</code> folder and type: <code>npm<strong> </strong>init</code></p>



<p>This will build out a basic <code>package.json</code> file that lists our application dependencies and scripts.</p>



<p>React needs a toolchain to build and render your code. We&#8217;ll start by installing the development dependencies.</p>



<p><code>npm install --save-dev @babel/cli @babel/core @babel/preset-env @babel/preset-react babel-loader webpack webpack-cli</code></p>



<p>After NPM installs the required dev dependencies we can install React.</p>



<p><code>npm install react react-dom</code></p>



<h3 class="wp-block-heading">Add Webpack Config File</h3>



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



<p>Place this code below in a file named <code>webpack.config.js</code></p>



<pre class="wp-block-code"><code>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: &#91;
     {
       test: /\.js$/,
       exclude: /(node_modules)/,
       use: {
         loader: 'babel-loader'
       }
     }
   ]
 },
};
 
module.exports = config;
</code></pre>



<h3 class="wp-block-heading">Edit package.json</h3>



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



<pre class="wp-block-code"><code> "scripts": {
   "build": "NODE_ENV=production webpack",
   "watch": "webpack --watch --progress"
 },</code></pre>



<p>Add the build and watch scripts to your package.json <code>scripts</code> key.</p>



<h3 class="wp-block-heading">Configure Babel</h3>



<p>We&#8217;ll need to add a babel key to our package.json file to tell Babel how to handle our application.</p>



<pre class="wp-block-code"><code> "babel": {
   "presets": &#91;
     &#91;
       "@babel/preset-env",
       {
         "targets": {
           "browsers": &#91;
             "IE &gt;= 11",
             "last 3 versions"
           ]
         }
       }
     ],
     "@babel/preset-react"
   ]
 }</code></pre>



<h3 class="wp-block-heading">Build Your App</h3>



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



<pre class="wp-block-code"><code>import React from 'react';
import { render } from 'react-dom';

const App = () =&gt; {
    return (
        &lt;div&gt;Hello React&lt;/div&gt;
    )
}

render(&lt;App /&gt;, document.querySelector('#myapp'));</code></pre>



<p>You should be able to run <code>npm run watch</code> to compile your app using development settings. Webpack will automatically watch your app&#8217;s files and recompile when they&#8217;re changed. When ready to deploy however it&#8217;s best to run <code>npm run build</code> to properly minimize the app for production.</p>



<p>Once built, you&#8217;ll see a new folder named <code>build</code>. Inside it will contain your <code>app.bundle.js</code> that we will include in our Backdrop module.</p>



<h3 class="wp-block-heading">Include Your App in Backdrop</h3>



<p>Back in our <code>.module</code> file we will need to change the output of our controller from  HTML to  a <strong>render array</strong>.</p>



<pre class="wp-block-code"><code>    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&#91;'content'] = array(
            '#type' =&gt; 'markup',
            '#markup' =&gt; '&lt;div id="myapp"&gt;Hello Html&lt;/div&gt;',
            '#attached' =&gt; array(
                'js' =&gt; array(
                    array(
                        'data' =&gt; $js_path,
                        'every_page' =&gt; FALSE,
                        'group' =&gt; JS_THEME,
                        'type' =&gt; 'file',
                        'preprocess' =&gt; FALSE,
                        'scope' =&gt; 'footer',
                    )
                ),
                'css' =&gt; array(
                    array(
                        'data' =&gt; $css_path,
                        'every_page' =&gt; FALSE,
                        'group' =&gt; CSS_THEME,
                        'type' =&gt; 'file',
                        'preprocess' =&gt; FALSE,
                        )
                    ),
                ),
            );
        return $page;
    }</code></pre>



<p>Instead of outputting HTML we&#8217;ve refactored our controller to output a backdrop <a href="https://docs.backdropcms.org/api/backdrop/modules%21examples%21render_example%21render_example.module/1">render array</a>. Importantly, we need to specify our scope as &#8216;footer&#8217; in order to have our JavaScript load after the DOM elements have been loaded.</p>



<h3 class="wp-block-heading">Conclusion</h3>



<p>We&#8217;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&#8217;t have to go fully headless just to use React.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://api.jaytria.com/2021/03/30/adding-react-to-backdrop-cms-a-guide-for-a-progressively-decoupled-application/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>

<!--
Performance optimized by W3 Total Cache. Learn more: https://www.boldgrid.com/w3-total-cache/

Page Caching using Disk: Enhanced 
Content Delivery Network via N/A
Lazy Loading (feed)
Minified using Disk
Database Caching 17/22 queries in 0.002 seconds using Disk

Served from: api.jaytria.com @ 2026-05-08 14:45:24 by W3 Total Cache
-->