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

5k views Asked by At

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);
1

There are 1 answers

1
RKichenama On BEST ANSWER

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