node.jsreactjsbabeljsreact-dom-serverbabel-register

How to load react component dynamically using require with babel-register


I am using babel-register to use ES6 classes in node environment and want to load and render React component dynamically using require(file_path) with ReactDomServer, but its showing me following error:

"Invariant Violation: renderToStaticMarkup(): You must pass a valid ReactElement."

// enable es6
require('babel-register')({
    "presets": ["es2015", "react"],
    "extensions": [".jsx", ".js"]
});

// load component
var testComponent = require(testComponentPath);

console.log(testComponent); // { default: [Function: TestComponent] }

var html = ReactDomServer.renderToStaticMarkup(testComponent);

Solution

  • Change your require statement to var testComponent = require(testComponentPath).default;, assuming the component is exported as default.