A Simple Route to Writing a React.js App in a WordPress Plugin

wordpress reactjs

We’ll start this article with a demo:

(In my mind, the correct answers are “C” for question one, and either “A” or “B” for question two, but it’s really up to you. Also, please feel free to download the plugin I used to make the quiz!)

Today I’ll teach you how to begin learning JavaScript app creation inside a familiar WordPress environment, without tangling with other complex technologies.

So what was that? It was a simple web application built in React.js, the hot-hot-hot JavaScript framework built by the genius billionaire playboys at Facebook and Instagram.

As Matt Mullenweg and everyone else agrees, JavaScript is the future of web development. And yet most of the coolest JavaScript technologies (other than jQuery) seem to call for their own full technology stacks—which puts a lot of learning all on your plate at once. But as I’m starting to figure out, it doesn’t have to be this way!

So the goal of today’s article is specific, and it’s not to teach you React.js itself (I’m still barely a beginner). Rather, today I’ll teach you how to start to learn app creation in React.js (and similar frameworks), inside a familiar WordPress environment, without tangling with the numerous other complex technologies that have tended to push me out of learning app development.

Approaching JavaScript Frameworks as a WordPress Professional

I’ve hesitated to get fully into JS frameworks because of the seeming need to learn a “full stack” all at once, which entails an overwhelming amount of learning.

I’ll be honest: web application development scares me somewhat. Working primarily in WordPress, building web apps feels like the “deep end of the pool”—and it’s also where all the “real” technology hangs out. It’s also where most of the cool stuff is—like Facebook, Twitter, Airbnb, Spotify, and so on—since to do most really cool things you need to be interacting deeply with users in a way that informational sites (which are WordPress’s best use case) don’t.

The major specific reason I’ve been slow to get deep into app development is what feels like the huge knowledge gap between WordPress work and other types of web development. To do a large project in React.js, you don’t need to just know React.js; you need to know a “full stack.” Such a full stack might look like: Node.js (or another back-end solution, perhaps a PHP framework); Grunt (or another task runner); Bower (or another package manager); probably a bunch of other tools I don’t know about; and finally a front-end JavaScript framework like Angular.js or React.js. It’s a lot to learn all at once—so I mostly haven’t.

You can start using front-end JavaScript frameworks inside WordPress, without interacting heavily with the site’s backend architecture.

If you’re in a similar place, today’s article might be good news. It turns out to be pretty easy to start using front-end JavaScript frameworks inside a WordPress environment, and without interacting heavily with the site’s backend architecture. In my experience so far, this is a great way to learn these frameworks.

How to Set Up a React.js App Through a WordPress Plugin

The remainder of this article will walk you through the setup of our React.js quiz app. The full code of the demo is available for download here, so dig in!

The Full Plugin PHP Code

Here’s the entirety of the plugin’s main PHP file:

<?php
/*
Plugin Name: WPShout React Quiz
Description: React.JS Quiz in WordPress!
Author: Press Up
Author URI: http://pressupinc.com
*/

// Shortcode to output needed markup
add_shortcode( 'wpshout_react_quiz', 'wpshout_react_quiz_show_quiz' );
function wpshout_react_quiz_show_quiz() {
	return '<div id="quiz"></div>';
}

add_action( 'wp_enqueue_scripts', 'wpshout_react_quiz_enqueue_scripts' );
function wpshout_react_quiz_enqueue_scripts() {
	// Only load for the specific post with the quiz demo
	if( ! is_single( 10742 ) ) {
		return;
	}

	wp_enqueue_script( 'react', plugin_dir_url( __FILE__ ) . 'react/build/react.min.js' );
	wp_enqueue_script( 'react-dom', plugin_dir_url( __FILE__ ) . 'react/build/react-dom.min.js' );
	wp_enqueue_script( 'babel', 'https://npmcdn.com/babel-core@5.8.38/browser.min.js', '', null, false );
	wp_enqueue_script( 'wpshout-react-quiz', plugin_dir_url( __FILE__ ) . 'wpshout-react-quiz.js' );

	wp_enqueue_style( 'wpshout-react-quiz', plugin_dir_url( __FILE__ ) . 'wpshout-react-quiz.css' );
}

// Add "babel" type to quiz script
add_filter( 'script_loader_tag', 'wpshout_react_quiz_add_babel_type', 10, 3 );
function wpshout_react_quiz_add_babel_type( $tag, $handle, $src ) {
	if ( $handle !== 'wpshout-react-quiz' ) {
		return $tag;
	}

	return '<script src="' . $src . '" type="text/babel"></script>' . "\n";
}

Let’s take a look at each key function.

add_shortcode(): Registering the Quiz Through a Shortcode

The easiest way to output the quiz is through a shortcode. This section uses add_shortcode() to create the following situation: Anytime a post contains the text [wpshout_react_quiz], WordPress outputs the following markup: <div id="quiz"></div>. This empty div is what the React.js script will fill with the quiz.

wp_enqueue_scripts: Selectively Enqueueing Scripts on Quiz Demo Page

This section involves a pretty primitive use of wp_enqueue_scripts(): I don’t want every page on WPShout to pull in React.js from now on, so I’m only enqueueing those scripts (and the plugin’s single stylesheet) on the single post with post ID 10742, which is the post you’re reading now.

The other important thing to note is that I’m pulling in Babel (a JS library that the React tutorials I’ve been reading rely on) remotely, by calling its specific address elsewhere on the web. Note the way the request is written: starting with // lets us pull in the resource securely over HTTPS, since WPShout (being under SSL) won’t pull in insecure resources.

The takeaway here is that, if there are stable external URLs where your needed JavaScript resources are located, and you don’t mind the potential performance implications of fetching them remotely, you can call them remotely rather than dragging them down directly into your plugin or using a package manager.

script_loader_tag: Enabling babel on Our Main JavaScript File

This is the most obscure piece of the plugin’s PHP code. It exists because our main JavaScript file needs to look like this:

<script src="https://wpshout.com/wp-content/plugins/wpshout-react-quiz/wpshout-react-quiz.js?ver=4.6" type="text/babel"></script>

Specifically, the text/babel piece there is critical: it’s what says that the file can use all the cool stuff we needed to pull in the babel library to do.

Now, how do we put text/babel into a script tag that we’ve enqueued the WordPress way? The only way I’m aware of is through WordPress’s lovely filter script_loader_tag, and through manually parsing strings as done in this function.

Notes on the PHP

The above details aside, the plugin doesn’t do much! It simply registers a very simple shortcode, and enqueues a few scripts and one stylesheet. This is appropriate, since all the heavy lifting should be done within our React.js app itself.

Working with the Rest of the Stack

This plugin avoids or ignores most of the elements in a typical technology stack, to focus on React.js itself.

The PHP isn’t the hard part here—and it’s not the part that has kept me from learning technologies like React.js. Rather, it’s all the technologies around front-end tools like React.js that have kept me off. This plugin avoids or ignores all of them—and how it does so is the next thing we’re going to explore.

No Relationship with Backend Architecture

If you want a JS app to trade data with WordPress’s database, the best way is through the WP-API. But learning the API is its own process, and it still hasn’t fully landed in WordPress core yet.

My quiz approaches (well, really, ignores) the problem by simply creating its own data, that is not linked to data anywhere else.

Specifically, JavaScript apps consume JSON objects, and so I’ve just written my questions into a JSON object in the main JS file directly. This file is wpshout-react-quiz.js, the React-using JavaScript file that does all the heavy lifting for the quiz. The quiz data looks like:

/* JSON data */
var myData = [
  { questionText: "Is introducing React.js into a WordPress environment difficult?", answers: [ "Yes", "No", "Not necessarily" ] },
  { questionText: "Do you want to learn how?", answers: [ "Sure!", "Well, okay", "Goodbye" ] }
];

I’ve also created an empty store, in the same file, for data about which answer you choose by clicking radio buttons:

var answerData = [];

If you’re doing simple projects—particularly to learn—consider simply writing and consuming JSON data directly in your app.

This data lives nowhere but in the JS app, and so it doesn’t know anything else about you and is completely lost anytime you refresh your browser. For a simple quiz, this is perfect!

In sum, if you’re doing relatively simple projects—particularly to learn—you might consider divorcing yourself from all questions of data storage, and simply write and consume your own JSON objects directly in your app.

No Package Management Tool

The right way to get React.js is definitely not to download it off the web. Why not? Well, by crystallizing the version of React.js you’re using, you’re signing up for ever-deepening technical debt as React.js itself continues to change and improve.

This is the precise question that package managers like Bower exist to solve. Here’s the thing, though: learning to use them means a lot of familiarity and comfort with the command line, which I’ve only got on my best days.

If you’re like me, and if you’re doing a simple project (especially to teach yourself), I recommend you just grab your packages directly off GitHub. That looks like this:

React.js files in FTP

You’ll take on technical debt, yes, but that doesn’t matter much for learning projects or other projects with a small scope or a short lifetime. More important is that getting Bower running is no longer an impediment to your learning.

Nothing Else

Keeping the tech simple let me learn the basics of React.js without being flooded by other hundred-hour learning curves.

What I’ve covered in this article is all the technology I’m using! Building the quiz involved nothing in the command line, nothing in Node.js, nothing with the WP-API, nothing with Git, Bower, Grunt, or Gulp—and I suppose the list goes on. That meant I could learn the basics of React.js without constantly getting flooded with other hundred-hour learning curves.

But Do Learn the Right Way

Just to be clear: The advice I’ve given in this article is, pretty much without exception, the “wrong way” to do professional app development. I strongly suggest you learn the right way, and I intend to do so as well. However, you need to start somewhere, and in my opinion it’s awfully nice to start with the thing that makes pretty quizzes that auto-update without jQuery-style DOM monitoring, rather than drowning in Node.js documentation for a fortnight.

Please React!

My hope is that this article reduces the felt barriers for WordPress developers who are curious about JavaScript frameworks like React. It really can be as simple as introducing React into a plugin, and then starting to learn React itself, and the results you’ll get can be modest but definitely useful to you or a client.

As always, please give us your questions and thoughts below!

Image credit: Paul Downey


15 Responses

Comments

  • vishnu says:

    Hello,

    Can you tell me the way to use this plugin in a wordpress page because, I uploaded the plugin file and activated it but I am not able to figure out a way to use this in my page.

    Thanks,
    vishnu

    • Fred Meyer Fred Meyer says:

      Hi Vishnu,

      You’ll need to do two things. First, you put it on a page with the shortcode [wpshout_react_quiz]

      Second, I added the following lines in to keep extra JavaScript off pages that don’t need it on WPShout. You’ll want to remove them from the plugin’s PHP file:

      if( ! is_single( 10742 ) ) {
      	return;
      }
      • james says:

        instead of:

        if( ! is_single( 10742 ) ) {
        return;
        }

        why not use has_shortcode() to check for the shortcode?

  • doug R says:

    hey – the opening code example doesn’t load: in the console I get a message “Fetching scripts with an invalid type/language attributes is deprecated and will be removed in M56, around January 2017. See https://www.chromestatus.com/features/5760718284521472 for more details.”. Browser: Chrome 55.0.2883.87 m (64-bit)

  • Ifeoluwa says:

    Hey, thanks for this concise tutorial. I have been trying to get react to work on a wordpress site and this just made it crystal clear. Great job

  • Dev says:

    Thanks for this article and glad to see the exploration of using React in WordPress. I think WordPress is great, but it feels like it isn’t keeping up with the other advancements in technology.

  • Gilbert says:

    How do you pass data from the plugin to PHP and then back from PHP to React?

    If your example, let’s say you include your plugin in a post with:
    [wpshout_react_quiz_show_quiz}data_object_here{/wpshout_react_quiz_show_quiz}

    and you pass the data object in there. Then, in the plugin PHP file, you will have

    add_shortcode( ‘wpshout_react_quiz’, ‘wpshout_react_quiz_show_quiz’ );
    function wpshout_react_quiz_show_quiz($atts = [], $content = null, $tag = ”) {
    return ”;
    }

    So, how do you pass the data object back to React?
    I have tried passing the $content (as a simpler example passing just a string) like:

    add_shortcode( ‘wpshout_react_quiz’, ‘wpshout_react_quiz_show_quiz’ );
    function wpshout_react_quiz_show_quiz($atts = [], $content = null, $tag = ”) {
    return ”;
    }

    but, it doesn’t work. Any suggestions?

Pingbacks