React App as a Wordpress Plugin rendered with Shortcode

In this article I’ll show you guys how to create a React Application as a Wordpress Plugin and additionally how to pass in data from PHP / Wordpress to your React App.

You can view this project in Github here: https://github.com/wbaxterh/ReactWithWP

It’s pretty simple to start — create a directory /yourplugin with your plugin’s name PHP (yourplugin.php) file like this:

That’s the basic Wordpress plugin syntax. Now let’s go and create our ReactApp inside of this plugin. If you’re working locally like I am — just open the plugin directory with VSCode.

Open up the terminal and enter the command:

Go through the steps in the terminal and it will create a package.json file for you.

Now install the WP Scripts from the wp-element package from Wordpress.org

I also then add a build script to the package.json file

We also need to create a Wordpress compatible webpack.config file like so:

Then I also create a style.css file — you can leave it blank for now. If you omit this then make sure to remove the import in the next code block.

Now we can get into the React App itself. Create a new folder in your plugin directory called /src

In the src folder create an index.js file like so:

Then create another file called App.js (your applications main component) and for this example we are going to print a simple “Hello World”

Okay — now that our React App is setup let’s go back to our plugins PHP file and add a shortcode to display the App

We are also using the wp_get_current_user() and the wp_localize_sript() functions to get and pass the email of the logged in user to our app.

Now let’s put some additional code to get and store our user info in our App.js file

Then in your terminal run

If this worked — then a build folder should have been created in your plugin directory. This is the compiled code necessary to run your app.

Now activate your plugin and add your shortcode to a page or post and see if it works!

It worked for me! You can see my user email being returned as well.

Thanks for reading — let me know your thoughts. This was inspired because I recently did a big project that used a React App as a plugin. This is also mainly based off of another article here: https://javascript.plainenglish.io/how-to-add-a-react-app-to-wordpress-pages-61aee723d607 Which helped me immensely!

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Wesley Huber

I'm 29 years old, Freelance Web Developer and Boardsports enthusiast