How to Integrate ReactJS and WordPress: A Step-by-Step Guide (Part 1)
Tags: react, wordpress, webdev, tutorial
Published: 2023-02-25 13:45:49



The integration of WordPress and ReactJS is a powerful combination that can help developers create dynamic, interactive websites with ease. By combining the power of both platforms, web developers have access tools and features that can significantly improve their workflow.

WordPress provides a solid foundation for creating content-driven sites with its intuitive user interface and wide range of themes and plugins. On the other hand, ReactJS is an open source JavaScript library used for building complex user interfaces quickly.

Requirements:
-     A working WordPress site
-     Access to your site source code
-     A working React app

## I. Config your ReactJS App to build with Webpack

### 1. Install Webpack to your app

Simply run

```bash
npm install webpack
```

I use babel-loader as my loader for this app, you can use others. Let’s install the loader as well

```bash
npm install babel-loader
```

### 2. Create Webpack config file

Please note that this is my over-simplified config, feel free to customize it to your liking. One note for this session is the output part, we need to set `libraryTarget` to `umd` in order for the React app after build can be import/use widely.

Create a new file and name it `webpack.config.js`.

```js
const path = require('path');

module.exports = {
    entry: "./src/index.js", // entry point of React app
    output: {
        path: path.resolve(__dirname, "build"), // output folder
        filename: "my-app.js", // name of the main output file
        library: "my-app", // `library` is required by `umd`
        libraryTarget: "umd", // This exposes your library under all the module definitions, allowing it to work with CommonJS, AMD and as a global variable.
    },
    devtool: 'inline-source-map',
    module: {
        rules: [
            {
                test: /\\.(jsx|js)$/,
                include: path.resolve(__dirname, 'src'),
                exclude: /node_modules/,
                use: [{
                    loader: 'babel-loader',
                    options: {
                        presets: [
                            '@babel/preset-env',
                            ["@babel/preset-react", { "runtime": "automatic" }]
                        ]
                    }
                }]
            },
            {
                test: /\\.css$/i,
                use: ["style-loader", "css-loader"],
            },
            {
                test: /\\.(jpe?g|png|gif|svg)$/i,
                type: "asset/resource"
            },
        ]
    }
}
```

>  Read more about **libraryTarget: umd** 
[Output | webpack](https://webpack.js.org/configuration/output/#librarytarget-umd)

### 3. Change your ReactJS App entry file

By default, `ReactJS` will not be included after build, we will manually inject React and `ReactDOM` to the window object.


![A really nice window](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/dtnphpamlu8yxp13vwyp.jpg)
<figcaption><p style="text-align: center; font-size: 10px;">
Photo by <a href="https://unsplash.com/@tannahhims?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText">Hannah Tims</a> on <a href="https://unsplash.com/wallpapers/desktop/windows?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText">Unsplash</a>
</p></figcaption>

Open the `src/index.js` file and add a few more lines
```js
import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>
);

// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
reportWebVitals(console.log);

// Add these lines 👇
window.React = React;
window.ReactDOM = ReactDOM;

window.renderApp = (root) => {
  if (root) {
    console.log('React App with element', root);
    ReactDOM.render(React.createElement(App), root);
  } else {
    console.log('React App with element root id');
    ReactDOM.render(React.createElement(App), document.getElementById("root"));
  }
};
```
### 4. Add a new script to build source code with Webpack

Open `package.json` and add a new script.

```json
"buildwp": "webpack --mode production && cp -R build/ /var/www/html/wp-content/themes/twentytwentythree"
// Or just
"buildwp": "webpack --mode production"
```
Let break it down.

- `webpack --mode production`: this is the main part of the script. Build the app in production mode, the source code will be in the build folder or whatever folder you choose in the webpack.config.js.
- `cp -R build/ /var/www/html/wp-content/themes/twentytwentythree`: I am using the *twentytwentythreetheme*, so I copy the newly built source code to the corresponded theme folder. Feel free to change the destination or just leave it out (don’t forget to remove `&&`) and copy/paste it later on your own.

### 5. Run build

Well, build it.

```bash
npm run buildwp
```

## II. Update WordPress site to import the ReactJS app
### 1. Copy the build folder into your WordPress theme folder

You can have something like:
```
themes/
├─ your-theme/
│  ├─ react-app/
│  │  ├─ my-app.js
│  │  ├─ my-app-xyz.js
```

### 2. Create a new page template for our ReactJS app

As you know, the React app needs to attach to an element on the DOM in order to do its jobs, and most of the time it’s a 
```html
<div class="root"></div>
```
But of-course you can change this to what ever you want. So let add a new file to your theme folder, name it `page-react.php`
```php
<?php /* Template Name: React page */ ?>
<div class="root"></div>
<script type="text/javascript" src="<?php echo get_stylesheet_directory_uri() . '/react-app/my-app.js' ?>"
```

Nice, we almost there. 🎉

Change `echo get_stylesheet_directory_uri() . '/react-app/my-app.js` to your copied ReactJS app built code.

> The name of the template is up to you, but the file name convention needs to follow the instruction `page-xxxx.php`. [Read more](https://developer.wordpress.org/themes/template-files-section/page-template-files/#page-templates-within-the-template-hierarchy)

### 3. Use the new Page template

Now, all we need to do left is in the WordPress Admin Dashboard itself. 

Go to **WP Admin → Pages → Add New**

Choose page Template to be React Page or your template name, then publish it.

![Choosing React Page as Template](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/10z1xkxepp5s4dit9ive.png)
<figcaption><p style="text-align: center; font-size: 10px;">
Choosing <b>React Page</b> as Template
</p></figcaption>

After published the page, access the new page and your React app should be there.

![A working ReactJS app inside a WordPress page](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/l1s8qcy74h1g0nzm6lob.png)
<figcaption><p style="text-align: center; font-size: 10px;">A working ReactJS app inside a WordPress page
</p></figcaption>

## III. Why would you want to combine WordPress and ReactJS?

One major benefit offered by integrating WordPress with ReactJS is improved performance as compared to traditional WordPress development methods such as PHP or HTML coding alone; it’s faster than either one on its own due to how efficiently data flows between them both when working together in tandem! Additionally, because all your website’s logic lives within the same environment (React), debugging becomes much easier too – no more jumping back-and-forth between different files trying track down errors!

Another advantage gained from this pairing lies within scalability; since everything runs through Javascript instead now there’s no need worry about compatibility issues when adding new features or expanding existing ones – just make sure they work properly inside your current setup first before deploying anything live onto production servers! Finally let’s not forget about SEO benefits: thanks again goes out here towards JS being able handle things like server side rendering which helps search engine crawlers index pages better thereby improving overall rankings across multiple engines over time (Google/Bing etc).

In conclusion then if you’re looking develop modern web applications quickly while enjoying great performance gains along way then consider leveraging both WordPress & Reaction together today – it could be just what need take projects next level!.

---

At **[DelightInCode](https://delightincode.com/)**, we offer our expertise and guidance throughout the entire process – from conception through launch. Our team of experienced professionals will work with you every step of the way, ensuring that your vision is realized in beautiful form and function.


So don’t hesitate – get in touch today if there’s anything at all we can do for you! With our help, launching a successful website has never been easier!