How to Enqueue React JSX File in WordPress

React is JavaScript library from Facebook that helps rendering of UI components. It is very easy to learn and you can start with small, simple things until you are used to it.

Right now it is hot topic in WordPress, with big application using it and it will take more roots when REST API is officially introduced. Those applications are more complex but you might want to start with simple example.

To do this, follow official docs which also lists that you can have separate file with your React JSX code. What is required is that you load React, React DOM, and Babel before this as per same guide. These files are loaded using standard wp_enqueue_script() function in WordPress, but JSX requires slightly modified code. Instead of <script src="http://example.com/file.js" type="text/javascript"></script> that is produced by wp_enqueue_script(), you need <script src="http://example.com/jsx.js" type="text/babel"></script>. Notice that type is changed.

You should start the same way you should enqueue any JavaScript file:


function md_jsx_enqueue() {
  // Use minified libraries if SCRIPT_DEBUG is turned off
  $suffix = ( defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ) ? '' : '.min';

  // Add React files
  wp_enqueue_script( 'react', 'https://cdnjs.cloudflare.com/ajax/libs/react/0.14.3/react' . $suffix . '.js', array(), null );
  wp_enqueue_script( 'react-dom', 'https://cdnjs.cloudflare.com/ajax/libs/react/0.14.3/react-dom' . $suffix . '.js', array( 'react' ), null );

  // Add Babel file
  wp_enqueue_script( 'babel', 'https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.34/browser' . $suffix . '.js', array(), null );

  // Add JSX file
  wp_enqueue_script( 'jsx', get_stylesheet_directory_uri() . '/js/jsx.js', array( 'react', 'react-dom', 'babel' ), '1.0' );
}
add_action( 'wp_enqueue_scripts', 'md_jsx_enqueue' );

Then, you should use script_loader_tag filter to modify output for that JSX file:


function md_modify_jsx_tag( $tag, $handle, $src ) {
  // Check that this is output of JSX file
  if ( 'jsx' == $handle ) {
    $tag = str_replace( "<script type='text/javascript'", "<script type='text/babel'", $tag );
  }

  return $tag;
}
add_filter( 'script_loader_tag', 'wis_wp_theme_script_loader_tag', 10, 3 );

Just compare if handle you have used when registering script is same as current one and replace beginning of output.

Leave a Reply

Comment Guidelines:
  • Your email address will not be published
  • Fields marked with * are required
  • If you want your picture next to comment, open an account at Gravatar
  • If you want to know if someone replied to your comment, check “Notify me of followup comments via e-mail”
  • You can use these HTML tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>