Use react in your wordpress plugins


I’m going to keep this to the point.

  • React is okay for front-end work. (this includes the front-end of the WP-admin)
  • WordPress is okay as a back-end framework.

It’s important to think about back-end and front-end separately.  (This is also true in classic WP development with jQuery and Ajax)

A nice way to keep front-end and back and separate, is to use the WP Rest API as a communication layer.

Instead of writing php code that echoes a bunch of HTML, you will write PHP code that echo’s a bunch of JSON.

React really loves JSON. It will use the JSON to build some nice looking interactive HTML. And at some point it will post some data back to WP.

So this is basically your applications:

  1. WP exposes some REST endpoints that can be called via HTTP to get some data.
  2. The React app fetches the date by calling the REST endpoint, and renders the HTML
  3. The user interacts with the React app.
  4. React sends some data back to WP.
  5. WP handles the POST requests, processes the data, and writes some stuff to the database, or sends some emails or whatever, and returns some more JSON data.
  6. React automatically renders the HTML based on the new application state.

Sounds complicated? Maybe. But have you ever though about how a WP application with jQuery tends to work?

  1. WP spits out some HTML to a page
    1. Meanwhile WP is also registering a callback function that will get will wait for $_POST[‘action’] and spit out some more HTML, or maybe some JSON if we’re smart.
  2. jQuery messes up the entire HTML structure of the application and at one point sends an Ajax request to WP with registered action and some data we collected from the input fields.
  3. The WP action hook collects the POSTED data and processes it. It will return some new stuff.
  4. Some data returns and jQuery messed some more with the HTML in order reflect the new state.