Rendering a React element to its initial HTML Ask Question

I’m trying to extract the initial HTML from react code on the server side. To do this, I’m using the official react-dom/server library function renderToStaticMarkup() referenced from the official react website ( Can’t link to it because I’m new ).

I’m reading a react source file, transpiling the JSX and ES6 syntax to CommonJS using Babel and then parsing the evaluated CommonJS to renderToStaticMarkup().

React code:

import React from 'react';

class Test extends React.Component {
    render() {
        return <p>Hello World!</p>;
    }
}

export default Test;

Server-side code:

const { renderToStaticMarkup } = require( 'react-dom/server');
const Babel = require( '@babel/core' );
const Fsp = require( 'fs' ).promises;

(async () => {
    let fileContent = await Fsp.readFile( 'react.js', 'utf-8' );

    let code = Babel.transform( 
        fileContent, 
        { 
            presets: [ '@babel/preset-env', '@babel/preset-react' ],
            comments: false,
            minified: true
        }).code;

    let component = eval( code );
    let result = renderToStaticMarkup( component );

    console.log( result );
})();

package.json

{
  "dependencies": {
    "@babel/core": "^7.3.3",
    "@babel/preset-env": "^7.3.1",
    "@babel/preset-react": "^7.0.0",
    "react": "^16.8.2",
    "react-dom": "^16.8.2"
  }
}

Doing this returns an empty string "" when it should return <p>Hello World!</p>

In order to solve this, I needed to use the React.createElement() function on the evaluated code.

let component = eval( code );
let result = renderToStaticMarkup( component );

should have been:

let component = React.createElement( eval( code ), { ...props } );
let result = renderToStaticMarkup( component );