Call   0208 3131682   Mon-Fri 9am-6pm
Tag

React Archives - Freelance Full Stack Developer in London, UK

Create a WordPress plugin that uses a React App

By | Javascript, React, Wordpress | 3 Comments

In this post I’ll describe how to create a simple Hello World plugin that gets its content from React.

The WordPress plugin will use a shortcode to generate its content from a React App ( the React App is built / bootstrapped using the Create React App cmd line tool ).

Prerequisite: I will presume you have Node already installed

  • Create a WP plugin
  • Create a React App within the plugin (using create React app)
  • Tweak the React app to make it easy to load in the WordPress plugin ( Shortcode), by disabling code splitting (for the asset files JS and CSS)

Create WP plugin

This will be a very basic plugin one php file, which I’ll pop in a folder in WP plugins dir e.g. [YOUR PATH]/wp-content/plugins/hello_world_react and inside that hello.php.

Create React App

In plugin dir (from cmd line) run:

e.g. cd to [YOUR PATH]/wp-content/plugins/hello_world_react and run above cmd.

In src/index.js change root to hello-world-react like below:

Tweak React app

We’ll make the app spit out one js file and one css file, so its easy to include in the WP plugin.

The next bit is more or less a copy / paste I found here (thanks Mark!) :

https://mtm.dev/disable-code-splitting-create-react-app

in React app first create folder (called scripts) and add an empty js file called build-non-split.js , then paste in the stuff below:

In the root dir of the react app run:

npm install rewire

in package.json

delete package-lock.json

run:

npm run-script build

Lets run it !

In wordpress admin plugins, activate the plugin.

Next create a page and add this shortcode:

[hello-world-react]

Next visit the page

And you should see the React App

References

https://mtm.dev/disable-code-splitting-create-react-app

https://mikhailroot.ru/react-app-embedded-into-wordpress-page/

https://dev.to/n1ru4l/configure-the-cra-public-url-post-build-with-node-js-and-express-4n8

https://stackoverflow.com/questions/65126062/use-create-react-app-inside-a-wordpress-plugin

Disclaimer: All content on this site, is use at your own risk (Always backup before changing anything in your software/database/servers etc). Techs change, go out of date etc...
I/we accept no liability if anything you use on this site adversely affects you.