How does browser converts HTML string received from server in react server side rendering into HTML DOM elements?

509 views Asked by At

I have started learning React Server Side Rendering. Then I configured "index.js" file as follows:

const express = require('express');
const app = express();
const React  = require('react');
const renderToString = require('react-dom/server').renderToString;
const Home = require('./client/components/home').default;

app.get('/', (req, res) => {
    const content = renderToString(<Home></Home>);
    res.send(content); // Statement1
});

app.listen(3000, ()=> {
    console.log("App listening to port 3000");
});

So, at Statement1 in above code, we are returning string form "Home" component (because "renderToString" converts HTML into string.

When I inspect DOM, I get following code:

<html>
<head></head>
<body cz-shortcut-listen="true">
<div data-reactroot="">I'm home component</div>
</body>
</html>

So, my question is that how browser is converting HTML string (received as response from server) into DOM elements, and how this "<body>" tag is being added?

1

There are 1 answers

2
Quentin On

Given that there is a cz-shortcut-listen attribute on the body start tag, I would assume that it is getting added by the renderToString and not the browser.

It is something of a leap to get to that conclusion by looking at the top level of the server-side code and the DOM inspector without looking at the generated HTML source at all.

(After doing some further reading, it seems that attribute is added by a plugin you have installed. My point about actually looking at the HTML source stands though).

Browsers will follow the the specification for parsing HTML documents which includes provisions for handling elements with tag omission rules like the body element.

It will start out in The "before html" insertion mode, find a div start tag and hit:

Create an html element whose node document is the Document object. Append it to the Document object. Put this element in the stack of open elements.

Switch the insertion mode to "before head", then reprocess the token.

And then that will trigger the creation of the head element and so on.