How to make a React.js WordPress Plugin

React WordPress Plugin - Default Output

Create React App is the new officially supported way to create single-page React apps. Here’s a tutorial to show you how to make a React.js WordPress Plugin using it.

Disclaimer: I’m not a WordPress or PHP developer. This may not be “best practice” but it works. If I ever find a better way, or if someone teaches me one, I’ll update this post.

Installation

You’ll need Node.js 4.x or higher to install the global package.

npm install -g create-react-app

This puts the create-react-app command in your path. Let’s use that to create a simple hello-world app.

Hello-World App

create-react-app react-hello-world

That will create a “react-hello-world” folder with the following contents:

Mode                LastWriteTime     Length Name
----                -------------     ------ ----
d----        27/08/2016     16:48            node_modules
d----        27/08/2016     16:47            src
-a---        27/08/2016     16:47        155 .gitignore
-a---        27/08/2016     16:47      24838 favicon.ico
-a---        27/08/2016     16:47        624 index.html
-a---        27/08/2016     16:48        417 package.json
-a---        27/08/2016     16:47      25316 README.md

I’m in Windows PowerShell, so you might get something a little different.

That’s it! Test it with npm start and see something like this at http://localhost:3000:

React WordPress Plugin - Default Output

React WordPress Plugin – Default Output

Creating the WordPress plugin files

For those like me who has no idea of PHP or WordPress development, creating a plugin can seem daunting. There are a lot of guides out there, but let’s boil it down to the basic steps.

Step 1 – File and folder naming

The least you need is a folder with a .php file inside it with the same name. We already have a folder called react-hello-world. So create a file called react-hello-world.php inside it with the following contents:

<?php
/*
Plugin Name: React-Hello-World
Description: Plugin created from react-create-app.
Version:     0.0.1
Author:      MyAppIncome
Author URI:  http://myappincome.co.uk
*/

Testing that in WordPress

For WordPress to see the plugin, it should be in the wp-content/plugins directory of where WordPress is installed.

To show this, I’ve create a folder called react-hello-world in wp-content/plugins and copied the react-hello-world.php file into it.

As the administrator, I then went to the plugins page and filtered “inactive” plugins:

React WordPress Plugin - Empty Plugin

React WordPress Plugin – Empty Plugin

“Plugin Name”, “Description”, “Version”, “Author” and “Author URI” values from the .php file show.

At the moment, the “Activate” link would do nothing. So let’s make it do something.

Step 2 – Packaging the React.js app

If you run npm run build you will end up with a build folder containing the following:

C:\react-hello-world\build> tree /F
Folder PATH listing
Volume serial number is 9A26-B7C8
C:.
│   favicon.ico
│   index.html
│
└───static
   ├───css
    │       main.9a0fe4f1.css
    │       main.9a0fe4f1.css.map
    │
   ├───js
    │       main.168caebe.js
    │       main.168caebe.js.map
    │
    └───media
            logo.5d5d9eef.svg

We’re not interested in the index.html file, as WordPress will be serving the HTML. But, we are interested in the JavaScript, CSS and Media that is packaged up. As you can see, that’s already split into separate folders for us.

Step 3 – Using these files in WordPress

Getting WordPress to use these files at the right time is also relatively simple. WordPress provides wp_enqueue_script to include the file you pass to it when your theme asks to render the header or the footer.

// add the CSS file to the header
wp_enqueue_style( 'prefix-style', plugins_url('css\main.9a0fe4f1.css', __FILE__) );

// add the JS file to the footer - true as the last parameter
wp_enqueue_script( 'plugin-scripts', plugins_url('js/main.350b4a43cde67bd603fc.js', __FILE__),array(),  '0.0.1', true );

All that’s left is to add a div with an id of “root” for React to render to.

The easiest way to achieve this is a simple echo statement inside a php function. This approach has a downside. The site admin needs to call the function somewhere within the sites theme.

That’s not exactly an easy thing for most end-users to do but was good enough for what I wanted. If/when I learn of a better way, I’ll update this post.

Edit react-hello-world.php to add the following text after the content we created earlier.

function wp_react_hello_world() {
  echo '<div id="root"></div>';
}

function include_react_files() {
    wp_enqueue_style( 'prefix-style', plugins_url('css\main.9a0fe4f1.css', __FILE__) );
    wp_enqueue_script( 'plugin-scripts', plugins_url('js/main.350b4a43cde67bd603fc.js', __FILE__),array(),  '0.0.1', true );
}

add_action( 'wp_enqueue_scripts', 'include_react_files' );

That’s almost it for php. Copy the css, js and media folders to wp-content\plugins\react-hello-world. Also copy the latest react-hello-world.php file to “deploy” it. You should have a folder structure within wp-content\plugins\react-hello-world like this:

│   react-hello-world.php
│
├───css
│       main.9a0fe4f1.css
│       main.9a0fe4f1.css.map
│
├───js
│       main.168caebe.js.map
│       main.350b4a43cde67bd603fc.js
│
└───media
        logo.5d5d9eef.svg

Activate your new plugin and we’re almost there. We now need to call wp-react-hello-world somewhere in our theme. Otherwise, react won’t have a root div to render to.

Step 4 – Add it to your theme

To do this “properly” you will want to use child themes. But I think that’s too complex for this tutorial.

As a proof of concept, the easier thing to do is add a new text widget.

As your site administrator. Go to Appearance->Widgets and drag a new “Text” widget to the top of your sidebar. Here’s a screenshot of how I did it:

React WordPress Plugin - Add Widget

React WordPress Plugin – Add Widget

Refresh your site now and look at your sidebar. You should see the Create React App demo, like this:

React WordPress Plugin - React Widget

React WordPress Plugin – React Widget

Where’s the spinning logo?! Unfortunately Create React App packages the files so the logo is loaded from http:///static/media/logo.5d5d9eef.svg. That’s sensible for them, but not for us.

Let’s fix that.

Step 5 – Horrible Manual Edits

Fixing this by hand is simple. If you open the .js file, and search for “logo.” you should find {e.exports=n.p+"static/media/logo.5d5d9eef.svg"}. Change that to {e.exports="wp-content/plugins/react-hello-world/media/logo.5d5d9eef.svg"}, i.e. where the file resides, and you’re good to go.

That’s it! We have WordPress plugin that uses React.

Conclusion

Creating a WordPress plugin that uses React.js is simple. Create React App packages the files for you so you can concentrate on functionality.

The process I’ve described above is purposefully manual. I want to show what files you need, where you can create them and where you need to deploy them. If you’re doing this a lot, it will be worth your time writing a script to automate the deployment.

There is also the horrible manual editing to include the correct path for the media images. I’m hoping one day to solve that, but for the moment, that’s beyond my skill. If I was planning on writing a lot of WordPress plugins it would be a priority, but for the moment it’s good enough.

I hope this getting started using React.js in a WordPress plugin tutorial was useful. If you have any problems, please let me know in the comments below.

2 Responses to “How to make a React.js WordPress Plugin”

  1. Gilbert says:

    I followed your instructions and it works fine.

    However, after that, I made a form to subscribe users to MailChimp, based on this article https://medium.com/@luclemo/using-jquery-and-the-mailchimp-api-to-get-around-the-already-subscribed-error-bab3f593a1ce, but I have problems fetching the data back from the server (when getting a response from MailChimp.

    Error during service worker registration: TypeError: Failed to register a ServiceWorker: A bad HTTP response code (404) was received when fetching the script.

    Do I have to include the service-worker.js generated in the build directory when building the react app? If so, where should I put it on the WordPress server?

Leave a Reply

Your email address will not be published. Required fields are marked *