Simple integration of your React app into existing WordPress website

Let’s say you developed a React app, that is working perfectly on your local machine and you want to integrate it to your WordPress website. It is very simple.

WordPress section

Wee need to include our javascript and css files into our website. We will use wp_enqueue_script and wp_enqueue_style for this. Let’s add some action:

add_action('wp_enqueue_scripts', 'enqueue_react_scripts');
function enqueue_react_scripts()
{
  // Add files only on frontpage
  if (is_front_page()){
    //scripts
    foreach (glob(get_template_directory() . '/js/react/js/*.js') as $file) {
      $filename = substr($file, strrpos($file, '/') + 1);
      wp_enqueue_script($file, get_template_directory_uri() . '/js/react/js/' . $filename, null, '1.0', true);
    }
    //styles
    foreach (glob(get_template_directory() . '/js/react/css/*.css') as $file) {
      $filename = substr($file, strrpos($file, '/') + 1);
      wp_enqueue_style($file, get_template_directory_uri() . '/js/react/css/' . $filename, null, '1.0');
    }
  }
}

This code checks if this is frontpage, and then includes all *.js files in your_theme/js/react folder with wp_enqueue_script and all *.css files in the same folder with wp_enqueue_style functions.

React section

Now simply copy all of your build files to your your_theme/js/react folder. You can leave html file 🙂

That’s it, your React app is ready to go on your WordPress website, create a page, add a container with your app id and it will work flawlessly.

  •  
  •  
  •  
  •  
  •  
  •