Search code examples
reactjsreact-server

Why ReactDOMServer.renderToString not returning raw HTML


I write a simple example to test ReactDOMServer.renderToString like this:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8" />
        <script src="https://unpkg.com/react@16/umd/react.development.js"></script>
        <script src="https://unpkg.com/[email protected]/umd/react-dom-server.browser.development.js"></script>
    </head>
    <body>
        <div id="app"></div>
        <script type="text/javascript">
          const e = React.createElement;

          class DivComponent extends React.Component {
            constructor(props) {
              super(props);
            }
            render() {
              return e(
                'div',
                {
                  className: 'div-component'
                },
                'This is a div'
              );
            }
          }
          document.getElementById('app').innerHTML = ReactDOMServer.renderToString(e('DivComponent'));
        </script>
    </body>
</html>

I am expecting it to render:

<div id="app">
    <div class="div-component">This is a div</div>
</div>

But what I actually get is:

<div id="app">
    <divcomponent data-reactroot=""></divcomponent>
</div>

Do I have some misunderstanding on ReactDOMServer.renderToString? How could I get raw HTML as what I expected?


Solution

  • You should pass the component itself, and not its name, it just a string it has no meaning.

    Pass a string when you want to render HTML elements as described in React docs.

    ReactDOMServer.renderToString(React.createElement(DivComponent));