Human Made, a well-known WordPress Development Agency, created a tool for using React in your WordPress Plugins or Themes. It is essentially, a wrapper of the react-scripts tool and you can find it here.
To install this tool in our plugin, we need to have npx installed. Be sure you have your nodejs version updated if you can’t use npx.
To use it, we need to go into our plugins folder wp-quiz-tut through the terminal (command line) and then type:
npx create-react-app --scripts-version react-wp-scripts --php-namespace="WPQR" inc/react-wp
--php-namespace="WPQR" we will set the PHP namespace of the tool so we can use it without worrying about breaking the site due to multiple usages of this tool. With
inc/react-wp we are defining the location of the tool.
If you get an error saying that the directory does not exist, just create an empty folder
react-wp inside the folder
Integrating with our Plugin
Now that the tool is installed, we need to integrate it with our plugin. Since our Quiz plugin will be done through a shortcode, we need to register a shortcode first.
Adding our Shortcode
This will be the simplest shortcode you’ve ever seen probably. Open our main file
wp-quiz-tut.php and inside the
load method add this:
We have now registered our shortcode
wpqr, but we still need to define the output of it. Let’s create the method
Can’t be simpler than that, right? We are only outputting the container of our Quiz because we will use React to put the rest of it inside the element
Now, we need to enqueue the scripts from the tool React WP Scripts. We will now hook our
enqueue method inside our
enqueue method will be responsible to load the tool.
Open a post or a page and add our shortcode there. For now, you won’t see anything.
Loading our App inside the shortcode
Open the file
inc/react-wp/src and we will just change the container of our App.
inc/react-wp and then run
Try opening the page with our shortcode now and you should see something similar to this.
Download the Plugin
This plugin will have everything on it except the folder
npm install while inside the folder
React WP Scripts Tool is a great tool to start using React inside of your plugins or themes. With just a few modifications, you can start writing React within minutes.
In the next tutorial, we will start writing our React Quiz app.