The easiest way to integrate React with Wordpress

Tom Lagier
Studio Lagier

--

It’s 2021. You’re a web developer who wants to make good choices about a web stack to recommend to your clients. Many of your clients have Wordpress websites and a deep comfort with that set of authoring tools. A migration would be costly and it’s not in the budget.

But you want to write some friggin’ React!

It’s more and more difficult to find non-React focused resources on the web, and anymore it feels like web projects without a bundler are the exception rather than the rule. Maybe you feel left behind by the industry standards, or want to use React-only libraries. Maybe you’re like me and work about 10x faster building out React components than you do futzing around with form state by hand.

If you did some searching, most of the content out there is how to build a whole React front-end on top of Wordpress’s REST API. That’s a good idea, but might be a bigger lift than you have the time for.

This was me about a month ago — a client website in Wordpress, some React apps that they wanted integrated, and no appetite for a big refactor. What’s a dev to do?

Introducing wordpress-shortcode-webpack-plugin!

It’s a plugin that lets you easily integrate your React apps built with webpack (including Create React App) with a Wordpress site using shortcodes. Grab it on NPM, or directly from GitHub.

What does it look like?

Pretty simple.

Run that, and you’ll get a zip file, my-awesome-plugin.zip in your build directory. Upload that to Wordpress as a plugin, and you’ll be able to use the shortcode [my-awesome-plugin-app] to render your app.

How does it work?

First, we generate a manifest of the files that Webpack is producing in the build using webpack-manifest-plugin. We write that out to a PHP file and include some loading logic which tells Wordpress which assets to load. We generate a shortcode for each entry in the Webpack build. We copy over all the assets from the build & zip the whole thing up as a Wordpress plugin, ready to drop into your site!

Any other features?

Sure, here’s a few:

  • Written in Typescript, definitions included.
  • Customize the Wordpress plugin file by providing your own template.
  • Adjust every field of the plugin header.
  • Coming soon: an esbuild plugin.

Hope you find it useful, drop me a note if you have any other tips or tricks for easily getting React and Wordpress to get along. Feel free to open an issue if you’ve got a feature that you’d like supported.

Cheers!

--

--

Tom Lagier
Studio Lagier

Tech enthusiast in Los Osos — graphics in the front-end is what I like to work on. Founder @StudioLagier