Loading React into WP
Create a child theme, or if you want to load React into a plugin, you can do this in a plugin.
Make sure you have node and npm installed globally in your machine.
Make sure you have some way to access the command line.
npm init in the child theme to enable it to use npm packages. You now see a package.json file in your child theme directory. Listed here are the libraries your application depends on. It's a bit like wp_enqueue_scripts, but for JS libraries. All the external libraries/scripts you need are listed under devDependencies or dependencies.
npm i --save-dev @wordpress/scripts to install the package as a dev dependency.
Now you have access to three key scripts that come with this package. wp-scripts build which will turn your React code into regular JavaScript and put it in a build folder, which you enqueue in your functions.php . wp-scripts start which does the same thing, but continuously, as it keeps watching for changes as you code in React, and processing those changes into regular JS whenever you save, and finally wp.element. This is a WordPress wrapper around React. So for example instead of React.createElement() you call wp.element.createElement.
Create an src folder in the child theme. wp-scripts build automagically builds your React code into regular old JavaScript. But in order to do this, it will expect an index.js file in an src folder.
Your file strucutre should look like this
themes
-- twentynineteen
-- twentynineteen-child
---- src
------ index.js
---- style.css
---- functions.php
---- package.json
---- package-lock.json
Your src/index.js is where you keep your React code. This file has nothing to do with WordPress. You need to use npm to convert this React code into regular JavaScript so you can enqueue it in your functions.php.
function HelloWorld() {
return <div>Hello World!</div>;
}
wp.element.render(<HelloWorld />, document.querySelector(`#main .entry-content`));
What the above code does is it gets React to find the first DOM element with the class .entry-content in #main and replaces that with a React element, in this case it is
Now you have the React Element, you can run npm run build in the command line. This will give you a build folder, so your folder structure now looks like this:
themes
-- twentynineteen
-- twentynineteen-child
---- build
------- index.js
------- index.js.map
------- index.asset.php
---- src
------ index.js
---- style.css
---- functions.php
---- package.json
---- package-lock.json
We only need concern ourselves with index.js. This is the file we enqueue in our functions.php.
function my_enqueue_theme_js()
{
wp_enqueue_script(
'my-theme-frontend',
get_stylesheet_directory_uri() . '/build/index.js', ['wp-element'],
true
);
}