zaro

How to integrate React app in WordPress?

Published in React WordPress Integration 3 mins read

Integrating a React application into WordPress primarily involves treating your React app as a static asset, packaging it within a custom WordPress plugin or theme, and then correctly enqueuing its files to render on specific pages or posts. This method allows you to leverage React's dynamic capabilities while using WordPress for content management and backend functionalities.

How to Integrate a React App in WordPress

Embedding a React application within WordPress can transform static pages into dynamic, interactive experiences. The process typically involves building your React app, creating a custom WordPress plugin to house its build files, and then enqueuing these files to display the app on the front end.

Step-by-Step Integration Guide

Follow these steps to successfully integrate your React application into your WordPress site:

1. Prepare Your React App 🎨

Before anything else, ensure your React application is ready for deployment. This means finalizing your development and making sure it's optimized for production.

  • Create Your React App: If you haven't already, use a tool like Create React App to bootstrap your project.
    npx create-react-app my-react-app
    cd my-react-app
    npm start # for development
  • Routing (Optional but Recommended): If your React app uses client-side routing (e.g., with React Router), ensure your application can handle being served from a sub-directory if necessary, or that your WordPress setup redirects appropriately. For a single-page app within WordPress, you might only need a single entry point.
  • API Calls: If your React app needs data from WordPress, consider using the WordPress REST API.

2. Check Your Build Folder 📁

Once your React app is complete, you'll need to create a production-ready build.

  • Generate Build Files: Navigate to your React app's root directory in your terminal and run the build command:
    npm run build
    # or yarn build
  • Inspect build Directory: This command creates a build folder (or dist for Vite/Webpack setups) in your project root. Inside, you'll find:
    • index.html: The main HTML file.
    • static/: A folder containing your compiled JavaScript, CSS, and other assets (images, fonts). These files are typically minified and optimized for performance.
    • Crucial files: Identify your main JavaScript file (e.g., static/js/main.<hash>.js) and CSS file (e.g., static/css/main.<hash>.css). These are what you'll enqueue in WordPress.

3. Create a Plugin Folder 🗂️

The most robust way to integrate a React app is by creating a dedicated WordPress plugin. This keeps your application self-contained and separate from your theme, making it portable and update-friendly.

  • Navigate to Plugins Directory: Access your WordPress installation via FTP or your hosting's file manager. Go to wp-content/plugins/.
  • Create a New Folder: Create a new directory for your plugin, for example, my-react-app-plugin. Choose a unique and descriptive name.

4. Create a Plugin File 📝

Inside your newly created plugin folder (my-react-app-plugin), create a main PHP file with the same name as your folder (e.g., my-react-app-plugin.php). This file will contain the necessary WordPress plugin header and the logic for enqueuing your React assets.

  • Add Plugin Header: The top of this PHP file must contain the plugin header to make WordPress recognize it as a plugin:

    <?php
    /**
     * Plugin Name: My React App Plugin
     * Description: Integrates a custom React application into WordPress.
     * Version: 1.0.0
     * Author: Your Name
     * License: GPL2
     */
    
    // Exit if accessed directly.
    if ( ! defined( 'ABSPATH' ) ) {
        exit;
    }
    
    // Your plugin code will go here

5. Upload Your React Build Files 🚀

Now, transfer the compiled React app into your new WordPress plugin.

  • Copy build Contents: Copy the entire contents of your React app's build folder (the index.html, static folder, asset-manifest.json, etc.) into your WordPress plugin's folder (wp-content/plugins/my-react-app-plugin/).
  • Recommended Structure: For better organization, you might create a subfolder within your plugin, like my-react-app-plugin/react-app/ and place all build files there.
    wp-content/plugins/
    └── my-react-app-plugin/
        ├── my-react-app-plugin.php
        └── react-app/
            ├── index.html
            └── static/
                ├── css/
                │   └── main.<hash>.css
                └── js/
                    └── main.<hash>.js

6. Activate Your Plugin 🎉

With the files in place, activate your custom plugin from the WordPress admin dashboard.

  • Navigate to Plugins: In your WordPress admin area, go to Plugins > Installed Plugins.
  • Activate: Locate "My React App Plugin" (or whatever you named it) and click Activate. While the plugin is active, it won't do anything visible on the front end yet, as you haven't told it where or when to load your React app.

7. Add Files to Your Theme 🖼️ & 8. Enqueue React Files in Your Theme 🖋️

This is the crucial step where you tell WordPress to load your React app's assets and provide a container for it to render. You'll typically do this through a custom page template in your theme and by enqueuing scripts/styles in your plugin.

A. Create a Container for React (in your Theme):

Your React app needs an HTML element to mount onto. This is usually a div with a specific ID, like root.

  • Option 1: Custom Page Template: Create a new page template in your active theme.

    • In your theme's directory (wp-content/themes/your-theme/), create a new PHP file, e.g., page-react-app.php.

    • Add the standard WordPress template header:

      <?php
      /**
       * Template Name: React App Page
       */
      get_header(); // Loads header.php
      ?>
      
      <div id="root"></div> <!-- This is where your React app will render -->
      
      <?php
      get_footer(); // Loads footer.php
      ?>
    • Create a new page in WordPress (Pages > Add New) and assign this template to it under "Page Attributes" > "Template".

  • Option 2: Embed within existing content: You can also insert <div id="root"></div> directly into a page/post using the HTML block editor.

B. Enqueue React Files (in your Plugin):

Now, modify your my-react-app-plugin.php file to enqueue your React app's main JavaScript and CSS files. These files are typically found in the static subfolder of your React build output.

  • Identify correct paths: In your my-react-app-plugin/react-app/static/js/ and my-react-app-plugin/react-app/static/css/ folders, find the main JS and CSS files (e.g., main.c4b9a.js, main.d2e1f.css). The hash (c4b9a, d2e1f) will be unique to your build.

  • Add Enqueue Function: Add the following function to your my-react-app-plugin.php file:

    <?php
    /**
     * Plugin Name: My React App Plugin
     * Description: Integrates a custom React application into WordPress.
     * Version: 1.0.0
     * Author: Your Name
     * License: GPL2
     */
    
    // Exit if accessed directly.
    if ( ! defined( 'ABSPATH' ) ) {
        exit;
    }
    
    function my_react_app_enqueue_assets() {
        // Only enqueue on specific page template or page ID
        // Replace 'react-app-page' with the slug of your WordPress page using the custom template
        // Or check by page ID: is_page( 'YOUR_PAGE_ID' )
        if ( is_page_template( 'page-react-app.php' ) || is_page( 'your-react-page-slug' ) ) {
            // Get plugin directory URL
            $plugin_url = plugin_dir_url( __FILE__ ) . 'react-app/';
    
            // Enqueue React app's CSS
            wp_enqueue_style(
                'my-react-app-style',
                $plugin_url . 'static/css/main.css', // Adjust if your main.css has a hash
                array(),
                '1.0.0' // Or use filemtime($path) for cache busting
            );
    
            // Enqueue React app's JavaScript
            wp_enqueue_script(
                'my-react-app-script',
                $plugin_url . 'static/js/main.js', // Adjust if your main.js has a hash
                array( 'wp-element' ), // Dependency on 'wp-element' for React apps
                '1.0.0', // Or use filemtime($path) for cache busting
                true // Load script in the footer
            );
    
            // Optional: Pass data from WordPress to React
            // For example, if your React app needs the WordPress API URL or a nonce
            wp_localize_script(
                'my-react-app-script',
                'wpReactApp',
                array(
                    'apiUrl' => esc_url_raw( rest_url() ),
                    'nonce'  => wp_create_nonce( 'wp_rest' ),
                )
            );
        }
    }
    add_action( 'wp_enqueue_scripts', 'my_react_app_enqueue_assets' );
    
    // Optional: Add the #root div directly if not using a custom page template
    // This function will add the root div to specific content areas.
    // Use with caution, as it might interfere with other content.
    function my_react_app_root_container( $content ) {
        // If on the target page, append the root div.
        // Again, replace 'your-react-page-slug' with the actual slug.
        if ( is_page( 'your-react-page-slug' ) && ! has_block( 'my-react-app/root', $content ) ) {
            $content .= '<div id="root"></div>';
        }
        return $content;
    }
    // add_filter( 'the_content', 'my_react_app_root_container' ); // Uncomment if you want to automatically add the root div
    • Important: React's create-react-app typically generates files like main.<hash>.js and main.<hash>.css. You should rename these to main.js and main.css respectively within your plugin's react-app/static/js/ and react-app/static/css/ folders for simpler enqueuing, or update the wp_enqueue_script and wp_enqueue_style calls with the exact hashed filenames.
    • The wp-element dependency is crucial as it ensures WordPress's built-in React library is loaded before your application.
    • The wp_localize_script function is excellent for securely passing server-side data (like API URLs or nonces) to your React frontend.

By following these steps, your React application will be served from your WordPress site, providing a powerful, dynamic component within your content management system.