gcorne / wp-react-boilerplate

Get started with using React in a WordPress plugin
129 stars 27 forks source link

A suggestion for conditional script loading #7

Open jamigibbs opened 7 years ago

jamigibbs commented 7 years ago

If we don't conditionally enqueue admin.js, which is rendering based on a specific DOM element (wp-react-component-library in this case), a console error will trigger on all pages other than the one created for the plugin.

Uncaught Error: Invariant Violation: _registerComponent(...): Target container is not a DOM element.

A solution would be to assign a global variable to add_menu_page and pass that into the enqueue hook to check conditionally:


static function admin_enqueue_scripts($hook) {
  global $menu_page;
  if ( $menu_page != $hook ) {
    return;
  }
  wp_enqueue_script( 'wp-react-boilerplate-admin', plugins_url( 'build/admin.js', __FILE__ ), array(), 'v0.0.1', true );
}

static function add_admin_page() {
  global $menu_page;

  $menu_page = add_menu_page(
    'WP React Component Library',
    'Component Library',
    'manage_options',
    'wp-react-component-library',
    array( 'WP_React_Boilerplate', 'render_component_library' )
    );
}
gcorne commented 7 years ago

Yeah, this was a bit sloppy on my part. I'll fix it up.

Odyno commented 7 years ago

Hello, if can help you, I have fixed this issue on PR https://github.com/gcorne/wp-react-boilerplate/pull/9