diff --git a/lib/assets/javascripts/react_ujs_mount.js b/lib/assets/javascripts/react_ujs_mount.js index f95577682..92813db49 100644 --- a/lib/assets/javascripts/react_ujs_mount.js +++ b/lib/assets/javascripts/react_ujs_mount.js @@ -42,6 +42,30 @@ } }, + // Get the constructor for a className + getConstructor: function(className) { + // Assume className is simple and can be found at top-level (window). + // Fallback to eval to handle cases like 'My.React.ComponentName'. + // Also, try to gracefully import Babel 6 style default exports + // + var constructor; + + // Try to access the class globally first + constructor = window[className]; + + // If that didn't work, try eval + if (!constructor) { + constructor = eval.call(window, className); + } + + // Lastly, if there is a default attribute try that + if (constructor && constructor.default) { + constructor = constructor.default; + } + + return constructor; + }, + // Within `searchSelector`, find nodes which should have React components // inside them, and mount them with their props. mountComponents: function(searchSelector) { @@ -50,10 +74,7 @@ for (var i = 0; i < nodes.length; ++i) { var node = nodes[i]; var className = node.getAttribute(window.ReactRailsUJS.CLASS_NAME_ATTR); - - // Assume className is simple and can be found at top-level (window). - // Fallback to eval to handle cases like 'My.React.ComponentName'. - var constructor = window[className] || eval.call(window, className); + var constructor = this.getConstructor(className); var propsJson = node.getAttribute(window.ReactRailsUJS.PROPS_ATTR); var props = propsJson && JSON.parse(propsJson);