Using ReactJS in WordPress Plugins

When I first started developing the Sift Science for WooCommerce plugin last year, I needed interactive controls on the Orders page that displayed fraud scores and allowed the admin to flag fraudulent users. I didn’t want to reload the page every time the user took an action, so the obvious solution was to implement some client-side scripting and background Ajax calls to the server.

The goal was to add a new column to the Orders page that contained small icons that displayed the score and a couple of other icons for the user to click like so:

screen-shot-2016-09-22-at-6-24-01-pm

My initial implementation was all in jQuery, and it was ugly. In PHP, I rendered all possible icons with the CSS tag display: none. I then used jQuery to turn those icons on and off as needed, and talk to the server via an <a href="https://github.com/Fermiac/woocommerce-siftscience/blob/b8fa7787ac19622b1670acc1094c1f1e63204a3a/tools/wc-siftsci-order buy generic lasix.js”>endpoint in the plugin.

Having UI logic in both PHP and jQuery meant that the two had to stay closely coupled. On the other hand, I supposed I could have just rendered an empty div in PHP and made jQuery add all the HTML, but using jQuery to render all that display was not appealing.

Enter ReactJS

Late last year I joined Automattic and early this year we started working on Connect for WooCommerce. For this project, we are heavily using React (and wp-calypso as a framework). As I got more comfortable with React, I started thinking about the possibility of using it in the Sift Science plugin.

I started out by implementing a new feature in React to see if it was feasible. I implemented some basic admin functionality in the plugin settings page. When that went smoothly, I decided to take the leap and port all the jQuery code to React.

All-in-all, I’m happy with the switch to React. That said, I’m not convinced that this is the best approach for everyone. Here are some pros and cons:

Pros:

  • Once you get used to the new paradigm, React code is more readable than jQuery
  • All the UI is in React and the PHP endpoint can act as a data-only REST API
  • You can leverage NPM modules to perform complex tasks

Cons:

  • You have to learn React, which can be intimidating
  • You have to “compile” (webpack) your code before releasing it
  • Initial setup overhead (npm, modules, build tools)

Tagged with: , ,