Skip to content

Commit f4462dc

Browse files
committed
add useContexts which takes an array of require.context
1 parent c8c57bb commit f4462dc

File tree

2 files changed

+47
-0
lines changed

2 files changed

+47
-0
lines changed

react_ujs/index.js

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ var ReactDOMServer = require("react-dom/server")
55
var detectEvents = require("./src/events/detect")
66
var constructorFromGlobal = require("./src/getConstructor/fromGlobal")
77
var constructorFromRequireContextWithGlobalFallback = require("./src/getConstructor/fromRequireContextWithGlobalFallback")
8+
var constructorFromRequireContextsWithGlobalFallback = require("./src/getConstructor/fromRequireContextsWithGlobalFallback")
89

910
var ReactRailsUJS = {
1011
// This attribute holds the name of component which should be mounted
@@ -72,6 +73,13 @@ var ReactRailsUJS = {
7273
this.getConstructor = constructorFromRequireContextWithGlobalFallback(requireContext)
7374
},
7475

76+
// Given an array of Webpack `require.context`,
77+
// try finding components with `require`,
78+
// then falling back to global lookup.
79+
useContexts: function(requireContexts) {
80+
this.getConstructor = constructorFromRequireContextsWithGlobalFallback(requireContexts)
81+
},
82+
7583
// Render `componentName` with `props` to a string,
7684
// using the specified `renderFunction` from `react-dom/server`.
7785
serverRender: function(renderFunction, componentName, props) {
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
// Make a function which:
2+
// - First tries to require the name
3+
// - Then falls back to global lookup
4+
var fromGlobal = require("./fromGlobal")
5+
var fromRequireContext = require("./fromRequireContext")
6+
7+
module.exports = function(reqctxs) {
8+
var fromCtxs = reqctxs.map((reqctx) => fromRequireContext(reqctx))
9+
return function(className) {
10+
var component;
11+
try {
12+
var index = 0, fromCtx, firstErr;
13+
do {
14+
fromCtx = fromCtxs[index];
15+
16+
try {
17+
// `require` will raise an error if this className isn't found:
18+
component = fromCtx(className)
19+
} catch (fromCtxErr) {
20+
if (!firstErr) {
21+
firstErr = fromCtxErr;
22+
}
23+
}
24+
25+
index += 1;
26+
} while (index < fromCtxs.length);
27+
if (!component) throw firstErr;
28+
} catch (firstErr) {
29+
// fallback to global:
30+
try {
31+
component = fromGlobal(className)
32+
} catch (secondErr) {
33+
console.error(firstErr)
34+
console.error(secondErr)
35+
}
36+
}
37+
return component
38+
}
39+
}

0 commit comments

Comments
 (0)