Skip to content

Instantly share code, notes, and snippets.

@Deraen
Last active April 25, 2021 13:02
Show Gist options
  • Save Deraen/4b2957ed3b8fe95c23f9693415a8b511 to your computer and use it in GitHub Desktop.
Save Deraen/4b2957ed3b8fe95c23f9693415a8b511 to your computer and use it in GitHub Desktop.
react-use-context-test.js
var vm = require("vm");
var fs = require("fs");
function nodeGlobalRequire(file) {
var _module = global.module,
_exports = global.exports,
exportedRequire = false;
// to circumvent Node.js environment detection in bundled libraries
global.module = undefined;
global.exports = undefined;
// to allow requires of Node.js libraries (i.e. platform libs) that
// couldn't be bundled for some reason
if(global.require == undefined) {
exportedRequire = true;
global.require = require;
}
vm.runInThisContext.call(global, fs.readFileSync(file), file);
global.exports = _exports;
global.module = _module;
if(exportedRequire) {
global.require = undefined;
}
}
nodeGlobalRequire("./react-17.0.2/react.development.js");
nodeGlobalRequire("./react-17.0.2/react-dom-server.browser.development.js");
var mycontext = React.createContext("default");
function comp(props) {
var v = React.useContext(mycontext);
return React.createElement("div",
null,
"Context (a=",
props.a,
"): ",
v
);
}
// Trying to mimick Reagent functional render impl.
function reagentRender(props) {
return props.render.apply(props.render, props.args);
}
try {
console.log(
ReactDOMServer.renderToStaticMarkup(
React.createElement(comp, {a: 1})
),
ReactDOMServer.renderToStaticMarkup(
React.createElement(
mycontext.Provider,
{value: "foo"},
React.createElement(comp, {a: 2})
)
),
ReactDOMServer.renderToStaticMarkup(
React.createElement(
mycontext.Provider,
{value: "foo"},
React.createElement(
React.memo(function reagentWrap(props) {
return reagentRender({render: comp, args: [props]});
}),
{a: 3}
)
)
)
);
} catch(e) {
console.error(e);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment