Skip to content

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

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!

Yay! 🎉 You made it to the end of the article!
Fred Meyer
Share:

14 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments
10+ Helpful Javascript Tutorials for WordPress Developers in 2017 | | Robert J Turner
August 22, 2017 4:46 am

[…] Price: Free | More Information […]

10+ Helpful Javascript Tutorials for WordPress Developers in 2017 | curate.tgit.me
August 21, 2017 7:25 am

[…] Price: Free | More Information […]

10+ Helpful Javascript Tutorials for WordPress Developers in 2017 | Professional WordPress Migration Services
August 21, 2017 7:05 am

[…] Price: Free | More Information […]

Gilbert
June 26, 2017 3:14 pm

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?

Dev
April 20, 2017 5:29 pm

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.

Ifeoluwa
February 4, 2017 7:44 am

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

The Best JavaScript Framework (For Me): Learning ReactJS Goes Better than Expected | WPShout
January 24, 2017 3:00 pm

[…] my experience, this makes React relatively easy to learn, because you’re just learning a new way to cause data to show up in the browser, without a […]

2016 Recap from a WordPress Developer - WILDE & wilde
December 8, 2016 11:29 pm

[…] JavaScript Framework – AngularJS ( Building Themes with AngularJS )  Vue.js – ( Creating a Theme with Vue.js )  and REACT ( a simple REACT.js App in a WordPress Plugin ) […]

vishnu
November 21, 2016 2:21 pm

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

james
January 24, 2017 7:37 pm
Reply to  Fred Meyer

instead of:

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

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

L’hebdo de l’écosystème WordPress n°55 - WPHebdo
August 30, 2016 12:22 am

[…] A Simple Route to Writing a React.js App in a WordPress Plugin – WPShout […]

Enlaces semanales sobre WordPress (#28) - Enlace Permanente
August 26, 2016 6:24 am

[…] A Simple Route to Writing a React.js App in a WordPress Plugin ¿Crees que es difícil encajar tus conocimientos de React con WordPress? ¿Estás aprendiendo alguna de las dos herramientas y quieres ver cómo usarlas conjuntamente. En este tutorial te explican cómo hacerlo. […]

#WordPressWednesday 2016 Volume 8
August 25, 2016 12:06 am

[…] Fred Meyer talks about React.js and writing a React.js app into a plugin. – A Simple Route to Writing a React.js App in a WordPress Plugin […]

Or start the conversation in our Facebook group for WordPress professionals. Find answers, share tips, and get help from other WordPress experts. Join now (it’s free)!