Problem loading React App in WordPress

I was having an issue trying to get a very simple Hello World React App to load in a WordPress page. The console error I was getting said that the element that I was trying to put the App into was not part of the DOM. When I looked through all of the DOM elements, my element was indeed there.

Here was the issue. The JavaScript for the React App was loading in the header of the WordPress post because I enqueued the script with only the first two arguments, which were the script name and script source. While reading wp_enqueue_script I realized that the last argument of the function was a boolean to determine if the script should be loaded at the end just before the </body> tag. Once I added the necessary arguments and included true, then my scripts loaded after the DOM element I was trying to use. And voila, my React App was working. Something so simple that can cause so many headaches.

Here is an example of my enqueue script, note the true argument at the end


/**
* Enqueue scripts
*/
function r3_enqueue_scripts(){
wp_enqueue_script( 'r3-react-app', plugin_dir_url( __FILE__ ) . 'assets/js/r3-react-app.min.js', array( 'jquery' ), '', true );
}
add_action( 'wp_enqueue_scripts', 'r3_enqueue_scripts' );

Add a Comment

Your email address will not be published. Required fields are marked *